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

python的魔术方法

2016-05-03 15:56 579 查看
持续更新

类:Example

实例:example = Example()

__str__
描述类的实例 print example

__repr__
描述类 print Example

__call__
调用实例 example() #=Example()()

__setattr__
实例属性赋值

__getattr__
获取实例属性值

class Book(object):
def __setattr__(self, name, value):
if name == 'value':
object.__setattr__(self, name, value - 100)
else:
object.__setattr__(self, name, value)
def __getattr__(self, name):
try:
return object.__getattribute__(name)
except:
return name + ' is not found!'
def __str__(self):
return ' cost : ' + str(self.value)

c = Book()
c.value = 101
print c.value #1
print c
print c.Type


__slots__
类所能包含的所有新建属性,继承自object类

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: