每个Python类都遵循以下内置属性,并且可以像其他任何属性一样使用点运算符来访问它们-
__dict__-包含类命名空间的字典。
__doc__-类文档字符串,如果未定义,则为无。
__name__-类名。
__module__-定义类的模块名称。在交互模式下,此属性为“ __main__”。
__bases__-包含基类的可能为空的元组,按基类在基类列表中的出现顺序排列。
对于上面的类,让我们尝试访问所有这些属性-
#!/usr/bin/python class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary print "Employee.__doc__:", Employee.__doc__ print "Employee.__name__:", Employee.__name__ print "Employee.__module__:", Employee.__module__ print "Employee.__bases__:", Employee.__bases__ print "Employee.__dict__:", Employee.__dict__
输出结果
执行以上代码后,将产生以下结果-
Employee.__doc__: Common base class for all employees Employee.__name__: Employee Employee.__module__: __main__ Employee.__bases__: () Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0xb7c84994>, 'empCount': 2, 'displayEmployee': <function displayEmployee at 0xb7c8441c>, '__doc__': 'Common base class for all employees', '__init__': <function __init__ at 0xb7c846bc>}