在 Python 中建立例項物件


要建立類的例項,使用類名呼叫類並傳遞其 __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.

使用以下函式代替普通語句來訪問屬性 −

  • getattr(obj, name[, default]) − 訪問物件的屬性。
  • hasattr(obj,name) − 檢查屬性是否存在。
  • setattr(obj,name,value) − 設定屬性。如果屬性不存在,則會建立它。
  • 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'

瞭解有關 Python 面向物件特性的更多資訊: Python 類和物件教程

更新時間: 29-八月-2023

35K+ 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.