类的特殊成员方法
- __doc__:显示类的描述
class Dog(object): ''' 描述狗狗的类 ''' print("一个方法") d = Dog() print(d.__doc__)
- __module__:输出模块 __class__:输出类
class C: def eat(self): print("eat")
from lib.aa import C class Dog(object): def eat(self): print("eat for dog") obj = C() print(obj.__module__) print(obj.__class__) d = Dog() print(d.__module__) print(d.__class__) ''' lib.aa <class 'lib.aa.C'> __main__ <class '__main__.Dog'> '''
- __call__ 使用:Dog()() 执行call方法
class Dog(object): ''' 描述狗狗的类 ''' def eat(self): print("一个方法") def __call__(self, *args, **kwargs): print("__call__",args,kwargs) d = Dog() d(1,2,3,4,name = "alex") Dog()(4,5,6,7,7,name = "alex")
- __dict__
class Dog(object): ''' 描述狗狗的类 ''' sex = "man" def __init__(self,name,age): self.name = name self.age =age def eat(self): print("一个方法") def __call__(self, *args, **kwargs): print("__call__",args,kwargs) print(Dog.__dict__)#类直接调用的时候,打印类里的所有属性,不包括实例属性 # {'__module__': '__main__', '__doc__': '\n 描述狗狗的类\n ', 'sex': 'man', '__init__': <function Dog.__init__ at 0x00000000024998C8>, 'eat': <function Dog.eat at 0x0000000002499950>, '__call__': <function Dog.__call__ at 0x00000000024999D8>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>} d = Dog("alex",12) print(d.__dict__)#实例调用的时候,打印实例的所有属性,不包括类的属性 # {'name': 'alex', 'age': 12}
- __str__:如果一个类中定义了该方法,那么打印对象时,默认输出该方法的返回值(能够辨别类对象)
class Dog(object): ''' 描述狗狗的类 ''' def __init__(self,name): self.name = name def eat(self): print("一个方法") def __call__(self, *args, **kwargs): print("__call__",args,kwargs) d = Dog("alex") print(d) # <__main__.Dog object at 0x00000000024E87F0>
class Dog(object): ''' 描述狗狗的类 ''' def __init__(self,name): self.name = name def eat(self): print("一个方法") def __call__(self, *args, **kwargs): print("__call__",args,kwargs) def __str__(self): return "<obj:%s>"%self.name d = Dog("alex") print(d) # <obj:alex>
- __getitem__ __setitem__ __delitem__
class Foo(object): def __init__(self): self.data = {} def __getitem__(self, key): print("__getitem__",key) def __setitem__(self, key, value): print("__setitem__",key,value) def __delitem__(self, key): print("__delitem__",key) obj = Foo() res = obj["a"] obj["name"] = "alex" del obj["name"]
class Foo(object): def __init__(self): self.data = {} def __getitem__(self, key): print("__getitem__",key) return self.data.get(key) def __setitem__(self, key, value): print("__setitem__",key,value) self.data[key] = value def __delitem__(self, key): print("__delitem__",key) obj = Foo() obj["name"] = "alex"#触发__setitem__ print(obj["name"])#触发__getitem__ print(obj.data) del obj["name"] #触发__delitem__
- __new__ :先于__init__方法调用