Python语法之面向对象思维导图
熊孩纸
阅读:733
2021-03-31 13:42:09
评论:0
Python3 相关功能代码:
import io
import sys
import math
# 调用reduce 函数
from functools import reduce
sys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8')
# Python3 高阶函数之函数即变量
# print函数赋值给变量p
p = print
# 通过变量p 调用print函数
p("高阶函数之函数即变量")
# Python3 高阶函数之传入函数
def add(x,y,z):
return abs(x) + abs(y)
result = add(-11,128,abs)
print("result is:",result)
# Python3 匿名函数
r = 10
area = lambda r:math.pi*r*r
print('半价为',r,'的面积为:',area(r))
# Python3 map 函数
number =[1,2,3,4,5,6,7,8,9]
print(list(map(lambda x: x*x, number)))
# Python3 reduce 函数
number =[1,2,3,4,5,6,7,8,9]
print(print(reduce(lambda x,y:x+y, number)))
# Python3 filter 函数
st =['A', '', 'C', 'D', '']
print(list(filter(lambda x: x and x.strip(),st)))
# Python3 sorted 函数之数字排序
a =[11,90,-1,20,17]
print(sorted(a))
# Python3 sorted 函数之字符串排序
aa =['a','12','b','z']
print(sorted(aa))
# Python3 之函数实现面向对象编程
#函数实现面向对象编程
def person(name,age,gender): #理解一个人种类
def play(name):
print("[%s],正在玩python" %(name['name']))
def eat(name):
print("[%s]正在吃饭"%(name["name"]))
def init(name,age,gender):
person1 = {
"name":name,
"age":age,
"gender":gender,
"play":play,
"eat":eat
}
return person1
return init(name,age,gender)
aa = person("肉肉",2,"male") #可以简单理解为生成了一个人的实例
aa["play"](aa) #调用人的方法
aa["eat"](aa)
# Python 3 类定义
class Data:
'''类定义'''
pass
obj = Data()
print(type(obj))
# Python3 类属性
class China:
people='Chinese'
print('China 类属性people:' + China.people)
# Python3 类方法
class English:
def speak(self):
print("%s 是个发达国家" %self)
country ='英国'
English.speak(country)
# Python3 输出类属性和方法方式一
print(dir(China))
# Python3 输出类属性和方法方式二
print(English.__dict__)
# Python3 输出类指定属性或方法
print(English.__dict__['speak'])
# Python3 实例对象
class Student:
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def score(self):
print("%s 成绩是99 "%self.name)
def play(self):
print("%s 喜欢玩球,年龄是 %s" %(self.name,self.age))
one = Student("肉肉",2,"male")
print(one.name)
one.score()
one.play()
# Python3 类的静态方法
class People(object):
def __init__(self, name):
self.name = name
@staticmethod
def eat(food):
print('肉肉 is eating %s' % food)
rourou = People('肉肉')
rourou.eat('牛肉')
# Python3 类方法
class Person(object):
name = '肉肉'
def __init__(self, name):
self.name = name
@classmethod
def eat(self, food):
print('%s is eating %s' % (self.name, food))
meta = Person('肉肉')
meta.eat('牛肉')
# Python3 静态属性之删除
class Man(object):
def __init__(self, name):
self.name = name
self.__food = None
@property
def eat(self):
print('%s is eating %s' % (self.name, self.__food))
@eat.setter
def eat(self, food):
# print('set food to eat', food)
self.__food = food
@eat.deleter
def eat(self):
del self.__food
sheep = Man('肉肉')
sheep.eat = '鹿肉'
sheep.eat
del sheep.eat
# Python3 之子类调用父类的方法
class Vehicle: # 定义交通工具类 父类
def __init__(self, name, speed, load, power):
self.name = name
self.speed = speed
self.load = load
self.power = power
def run(self):
print('开动啦...')
class Subway(Vehicle): # 地铁 子类
def __init__(self, name, speed, load, power, line):
super(Subway,self).__init__(name,speed,load,power) #注:调用父类的属性
self.line = line
def run(self):
print('地铁%s号线欢迎您' % self.line)
super(Subway,self).run() #子类调用父类的方法supper
line13 = Subway('中国地铁', '180m/s', '1000人/箱', '电', 13)
line13.run()
# Python3 之面向对象之类型判断
class Foo(object): #父类
pass
class Bar(Foo): #父类的派生类
pass
print(issubclass(Bar, Foo)) #True
# Python 3 面向对象之反射
class BlackMedium:
feature='Ugly'
def __init__(self,name,addr):
self.name=name
self.addr=addr
def sell_house(self):
print('%s 黑中介卖房子啦,傻逼才买呢,但是谁能证明自己不傻逼' %self.name)
def rent_house(self):
print('%s 黑中介租房子啦,傻逼才租呢' %self.name)
b1=BlackMedium('万成置地','回龙观天露园')
# 检测是否含有某属性
print(hasattr(b1,'name'))
print(hasattr(b1,'sell_house'))
# 获取属性
n=getattr(b1,'name')
print(n)
func=getattr(b1,'rent_house')
func()
# 设置属性
setattr(b1,'sb',True)
setattr(b1,'show_name',lambda self:self.name+'sb')
print(b1.__dict__)
print(b1.show_name(b1))
# 删除属性
delattr(b1,'addr')
delattr(b1,'name')
#delattr(b1,'show_name111')#不存在,则报错
# Python3 之getattr__和__getattribute__
class Foo:
# def __setattr__(self, key, value):
# print("setaaaa")
# self.__dict__[key] = value
def __getattr__(self, item): #可以把__getattr__和__getattribute__分别注释看看
print("执行getattr")
def __getattribute__(self, item):
print("执行attribute") #无论有没有该属性,都执行
raise AttributeError("这是错误异常") #遇到异常 ,去执行__getattr__
#raise 错误属性 ("抛出异常的错误内容")
aa = Foo()
aa.ssssss #不存在该属性会执行__getattribute__xxxxxxxxxx
#__setitem__,__getitem,__delitem__
class Foo:
def __init__(self,name):
self.name = name
def __getitem__(self, item):
print("执行getitem")
return self.__dict__[item]
def __setitem__(self, key, value):
print("执行setitem") #为了让效果明显所以用print
self.__dict__[key] = value
def __delitem__(self, key):
print("del obj[key],执行")
self.__dict__.pop(key)
def __delattr__(self, item):
print("del obj.key,执行")
self.__dict__.pop(item)
n = Foo("xiaoxi")
# print(n.__dict__)
# del n.name #执行delattr
# del n["name"] #执行delitem
n["age"] = 18 #执行setitem
print(n["age"]) #执行getitem
# __setattr__,__delattr__,__getattr__
class Foo1:
x=1
def __init__(self,y):
self.y=y
def __getattr__(self, item):
print('----> from getattr:你找的属性不存在')
def __setattr__(self, key, value):
print('----> from setattr')
# self.key=value #这就无限递归了,你好好想想
self.__dict__[key]=value #应该使用它
def __delattr__(self, item):
print('----> from delattr')
# del self.item #无限递归了
self.__dict__.pop(item)
#__setattr__添加/修改属性会触发它的执行
f1=Foo1(10)
print(f1.__dict__) # 因为你重写了__setattr__,凡是赋值操作都会触发它的运行,你啥都没写,就是根本没赋值,除非你直接操作属性字典,否则永远无法赋值
f1.z=3 #添加
print(f1.__dict__)
#__delattr__删除属性的时候会触发
f1.__dict__['a']=3#我们可以直接修改属性字典,来完成添加/修改属性的操作
del f1.a
print(f1.__dict__)
#__getattr__只有在使用点调用属性且属性不存在的时候才会触发
f1.xxxxxx
# _str__,__repr__
class Bar:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
print("this str")
return "名字是%s age%s" %(self.name,self.age)
def __repr__(self): #转换字符串,在解释器中执行
print("thsi repr")
return "%s" %self.name
test = Bar("xi",10)
print(test)
print(test.__repr__()) #print(repr(test)) 执行的是__repr__
# __format__
#和生成实例化对象的内容相对应
menu = {"ymd":"{0.year}{0.month}{0.day}",
"y-m-d":"{0.year}-{0.month}-{0.day}"}
class Foo:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_spec): #format_spec指定格式化的类型
# print(format_spec,self)
if not format_spec or format_spec not in menu: #如果没有传入格式,或则在menu中没有这个格式
format_spec = "ymd" #则格式化的默认格式是ymd ,在menu中有
fm = menu[format_spec] #通过menu字典格式化成相应格式的类型
# print(fm)
return fm.format(self) #把对象传入,格式化的内容
ss = Foo(2016,12,26)
# print(format(ss,"ymd"))
print(format(ss,"y-m-d"))
print(format(ss,"4565456"))
# __next__和__iter__
class Foo:
def __init__(self,n):
self.n = n
def __iter__(self):
return self
def __next__(self):
if self.n ==15:
raise StopIteration("已经迭代完了") #抛出异常的提示信息 StopIteration: 已经迭代完了
self.n += 1
return self.n
aa = Foo(10)
print(aa.n)
print(next(aa))
print(next(aa))
print(next(aa))
print(next(aa))
print(next(aa))
print(next(aa))
参考文章地址:https://www.cnblogs.com/keme/p/6220853.html#auto_id_15
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。