__ doc __ 表示类的描述信息
class Foo:
""" 描述类信息,这是⽤于xxx """
def func(self):
pass
print(Foo.__doc__)
#输出:类的描述信息
__ module__ 表示当前操作的对象在哪个模块(__ main __ )
__ class __ 表示当前操作的类是什么
test.py
class Person(object):
def __init__(self):
self.name = 'laowang'
main.py
from test import Person
obj = Person()
print(obj.__module__) # 输出 test 即:输出模块
print(obj.__class__) # 输出 test.Person 即:输出类
__ new__ 创建对象时为对象分配空间,在初始化方法 __ init__ 之前被调用
__ init__ 初始化方法,通过创建对象时,自动触发执行,一般用来定义实例属性
__ del__ 当对象在内存中被释放时,自动触发执行,是由解释器在进行垃圾回收时⾃动触发执行的。
__ call__ 对象后面加括号,触发执行,,例如对象()或者类名()()
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = Foo() # 执⾏ __init__
obj() # 执⾏ __call__
__ dict__ 类或对象的所有属性
class Province(object):
country = 'China'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print('func')
# 获取类的属性,即:类属性、方法、
print(Province.__dict__)
# 输出:{'__dict__': <attribute '__dict__' of 'Province' objects>, '__module__': '__main__', 'country': 'China', '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Province' objects>, 'func': <function Province.func at 0x101897950>, '__init__': <function Province.__init__ at 0x1018978c8>}
obj1 = Province('山东', 10000)
print(obj1.__dict__) # 获取 对象obj1 的属性 输出:{'count': 10000, 'name': '山东'}
obj2 = Province('山西', 20000)
print(obj2.__dict__) # 获取 对象obj1 的属性,输出:{'count': 20000, 'name': '山西'}
__ str__ 在打印对象时,默认输出该方法的返回值(字符串)
lass Foo:
def __str__(self):
return 'laowang'
obj = Foo()
print(obj) # 输出:laowang