Mọi lớp Python đều giữ các thuộc tính built-in sau và chúng có thể được truy cập bằng toán tử chấm như bất kỳ thuộc tính nào khác:
- __dict__ - Dictionary chứa namespace của lớp.
- __doc__ - Chuỗi tài liệu của lớp hoặc none nếu chưa định nghĩa.
- __name__ - Tên lớp.
- __module__ - Tên module nơi lớp được định nghĩa. Thuộc tính này là "__main__" trong chế độ tương tác.
- __bases__ - Một tuple có thể rỗng chứa các lớp cơ sở, theo thứ tự xuất hiện trong danh sách lớp cơ sở.
Ví dụ
Đối với lớp trên, hãy thử truy cập tất cả các thuộc tính này:
#!/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__
Kết quả
Khi mã trên được thực thi, nó cho kết quả sau:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': , 'empCount': 2, 'displayEmployee': , '__doc__': 'Common base class for all employees', '__init__': }