Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แอตทริบิวต์ในตัวของคลาส (Built-In Class Attributes) ใน Python

ทุกคลาส Python เก็บแอตทริบิวต์ในตัวต่อไปนี้ และสามารถเข้าถึงได้ด้วย dot operator เหมือนแอตทริบิวต์อื่นๆ:

  • __dict__ - Dictionary ที่มี namespace ของคลาส
  • __doc__ - สตริงเอกสารของคลาส หรือ none หากไม่ได้กำหนด
  • __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__

ผลลัพธ์ (Output)

เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

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__': }