__doc__ 返回类的表述信息
class Person(object): ''' 这是用来描述人的类 ''' p = Person() print(p.__doc__)
# 这是用来描述人的类
__module__ 和__class__
__module__ 返回所属模块
__class__ 返回所属类
print(p.__module__)
print(p.__class__)
__main__ # 表示当前模块?
<class '__main__.Person'> # Person类
__call__ 对象后面加括号,出发执行
class Person(object): ''' 这是用来描述人的类 ''' def __call__(self): print('执行call') p = Person() p()
# 执行call
__dict__ 以字典的形式返回(类或对象)里的属性和方法
class Person(object): ''' 这是用来描述人的类 ''' sex = 'man' def __init__(self, age): self.age = age def __call__(self): print('执行call') p = Person(18) print(Person.__dict__) # 输出类的属性和方法 print(p.__dict__) # 输出实例的属性和方法 {'__call__': <function Person.__call__ at 0x000002B0AA2CF840>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__module__': '__main__', 'sex': 'man', '__doc__': ' 这是用来描述人的类 ', '__dict__': <attribute '__dict__' of 'Person' objects>, '__init__': <function Person.__init__ at 0x000002B0AA2CF7B8>} {'age': 18}
__str__ 定义打印打印对象时,打印的内容
class Person(object): ''' 这是用来描述人的类 ''' def __str__(self): return 'skr' p = Person() print(p) # skr
__getitem__、__setitem__、__delitem__ 用于索引操作,分别表示获取、设置、删除数据
class Person(object): ''' 这是用来描述人的类 ''' def __getitem__(self, key): print('get %s' % key) def __setitem__(self, key, value): print('set %s is %s' % (key, value)) def __delitem__(self, key): print('delete %s' % key) p = Person() p['age'] p['name'] = 'Allen' del p['sex']
get age
set name is Allen
delete sex
__new__ 用来创建实例
属性__metaclass__可以用来设置该类由谁实例化创建。
class Person(object): ''' 这是用来描述人的类 ''' def __new__(cls, *args, **kwargs): print('skr') def __init__(self): print('666') p = Person() # skr
class Person(object): ''' 这是用来描述人的类 ''' def __new__(cls, *args, **kwargs): print('skr') return object.__new__(cls) def __init__(self): print('666') p = Person() # skr # 666
说明在__new__里调用的__init__
特殊方式创建类
def func(self): print 'skr' Foo = type('Foo', (object,), {'func': func})
类是由type类实例化产生。