ในการสร้างอินสแตนซ์ของคลาส คุณเรียกคลาสโดยใช้ชื่อคลาสและส่งผ่านอาร์กิวเมนต์ที่เมธอด __init__ ยอมรับได้
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000) คุณเข้าถึงแอตทริบิวต์ของวัตถุโดยใช้ตัวดำเนินการจุดกับวัตถุ ตัวแปรคลาสสามารถเข้าถึงได้โดยใช้ชื่อคลาสดังนี้ -
emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
ตัวอย่าง
ตอนนี้นำแนวคิดทั้งหมดมารวมกัน -
#!/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
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount ผลลัพธ์
เมื่อโค้ดด้านบนถูกรัน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Name : Zara ,Salary: 2000 Name : Manni ,Salary: 5000 Total Employee 2
คุณสามารถเพิ่ม ลบ หรือแก้ไขคุณสมบัติของคลาสและอ็อบเจ็กต์ได้ตลอดเวลา -
emp1.age = 7 # Add an 'age' attribute. emp1.age = 8 # Modify 'age' attribute. del emp1.age # Delete 'age' attribute.
แทนที่จะใช้คำสั่งปกติเพื่อเข้าถึงแอตทริบิวต์ คุณสามารถใช้ฟังก์ชันต่อไปนี้ได้ -
- The getattr(obj, name[, default]) − เพื่อเข้าถึงแอตทริบิวต์ของวัตถุ
- The hasattr(obj,name) − เพื่อตรวจสอบว่าแอตทริบิวต์มีอยู่หรือไม่
- The setattr(obj,name,value) - เพื่อตั้งค่าแอตทริบิวต์ หากไม่มีแอตทริบิวต์ก็จะถูกสร้างขึ้น
- The delattr(obj, name) − เพื่อลบแอตทริบิวต์
hasattr(emp1, 'age') # Returns true if 'age' attribute exists getattr(emp1, 'age') # Returns value of 'age' attribute setattr(emp1, 'age', 8) # Set attribute 'age' at 8 delattr(empl, 'age') # Delete attribute 'age'