您的位置:首页 > 编程语言 > Python开发

python3.6面向对象的多继承与装饰器

2017-03-27 23:26 295 查看
# 多继承
class A:
def show(self):
print('AAAA')

class B:
def fun(self):
print('BBBB')

class C(B,A):
pass

x = C()

# 类的特殊方法
'''
类属性:
__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
'''
x = 'a\nb'
#print(repr(x))
#实例调用:
'''
__init__ 初始化
__repr__ c1
__str__ print (c1 )(如果类里面先定义了__repr__的话print x时也会返回对应的
__call__ c1() 使实例可被调用
'''
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
def __str__(self):
return '宽为%s,高为%s'%(self.width,self.height)
def __repr__(self):
return '面积为%s'%self.area()
def __call__(self):
return '哈哈哈 '
def area(self):
return self.width*self.height
def __add__(self,other):
if isinstance(other,Rectangle):
return self.area()+other.area()

c1 = Rectangle(3,4)
c2 = Rectangle(5,6)
# 运算符魔法方法:
'''
__add__(self,other) x+y
__sub__(self,other) x-y
__mul__(self,other) x*y
__mod__(self,other) x%y
__iadd__(self,other) x+=y
__isub__(self,other) x-=y
__radd__(self,other) y+x
__rsub__(self,other) y-x
__imul__(self,other) x*=y
__imod__(self,other) x%=y
'''
# 装饰器
'''
@property 装饰过的函数返回的不再是一个函数,而是一个property对象
装饰过后的方法不再是可调用的对象,可以看做数据属性直接访问。
@staticmethod 把没有参数的函数装饰过后变成可被实例调用的函数,
函数定义时是没有参数的。
@classmethod 把装饰过的方法变成一个classmethod类对象,既能能被类调用又能被实例调用。
注意参数是cls代表这个类本身。而是用实例的方法只能被实例调用。
'''
class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
@property
def area(self):
return self.width*self.height
@staticmethod
def fun():
return 'xxxxxx'
@classmethod
def show(cls):
print(cls)
return 'YYYY'
c1 = Rectangle(3,4)
def fun1(ff):
def fun2(y):
return ff(y)+100
return fun2

@fun1 #ff = fun1(ff) # x=ff
def ff(y):
return y*y

def filterarg(x):
def fit(*arg):
if len(arg) == 0:
return 0
for i in arg:
if not isinstance(i,int):
return 0
return x(*arg)
return fit

#@filterarg
def sums(*arg):
return sum(arg)

filterarg(sums)(3,4,5)

@filterarg
def average(*arg):
print(arg)
return sum(arg)/len(arg)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息