马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 汪蛋 于 2017-9-19 11:46 编辑
知识点一:优雅地访问属性:gtrattrclass C():
def __init__(self):
self.x = 'X-man'
>>> c = C()
>>> c.x
'X-man'
>>> getattr(c, 'y', '没有这个属性')
'没有这个属性'
知识点二:优雅地访问属性:propertyclass C():
def __init__(self, size=10):
self.size = size
def getSize(self):
return self.size
def setSize(self, value):
self.size = value
def delSize(self):
del self.size
x = property(getSize, setSize, delSize)
>>> c = C()
>>> c.x
10
>>> c.x = 1
>>> c.x
1
>>> c.size
1
>>> del c.x
>>> c.size
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
c.size
AttributeError: 'C' object has no attribute 'size'
知识点三:魔法方法的属性访问class C():
def __getattribute__(self, name):
print("getattribute")
return super().__getattribute__(name)
知识点四:小程序练习class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def __setattr__(self, name, value):
if name == 'square':
self.width = value
self.height = value
else:
super().__setattr__(name, value)
#或者super这一条语句换成下面
#self.__dict__[name] = value
#如果写成self.name = value就会进入死循环
def getArea(self):
return self.width * self.height
>>> r1 = Rectangle()
>>> r1.getArea()
0
>>> r1 = Rectangle(2, 3)
>>> r1.getArea()
6
>>> r1.square = 10
>>> r1.width
10
>>> r1.height
10
>>> r1.getArea()
100
>>> r1.__dict__
{'width': 10, 'height': 10}
|