首頁  >  文章  >  後端開發  >  如何在Python中找到物件的方法或屬性?

如何在Python中找到物件的方法或屬性?

王林
王林轉載
2023-09-17 16:01:02815瀏覽

如何在Python中找到物件的方法或屬性?

要尋找物件的屬性,請使用 Python 中的 getarr() 方法。若要檢查屬性是否存在,請使用 hasattr() 方法。使用 Python 中的 setattr() 方法設定屬性。

存取物件的屬性

範例

要存取物件的屬性,我們將使用 Python 中的 getattr() 方法 -

class student:
   st_name ='Amit'
   st_age ='18'
   st_marks = '99'
   def demo(self):
      print(self.st_name)
      print(self.st_age)
      print(self.st_marks)

# Create objects
st1 = student()
st2 = student()

# The getattr() is used here
print ("Name = ",getattr(st1,'st_name'))
print ("Age = ",getattr(st2,'st_age'))

輸出

Name = Amit
Age = 18

存取和設定類別屬性

範例

在此範例中,為了設定屬性,我們將使用 setattr() 方法。

class student:
   st_name ='Tim'
   st_age ='18'
   def demo(self):
      print("Hello from demo() function")

# The getattr() is used here
print(getattr(student,'st_name'))

# Returns true if object has attribute
print(hasattr(student,'st_age'))

# Set additional attribute st_marks
setattr(student,'st_marks','95')

# Get Attribute
print(getattr(student,'st_marks'))

# Checking for an attribute
print(hasattr(student,'demo'))

輸出

Tim
True
95
True

訪問方法

範例

在這個例子中,我們將學習如何存取方法 -

class student:
   st_name ='Tim'
   st_age ='18'
   def demo(self):
      print("Hello from demo() function")

# The getattr() is used here
print(getattr(student,'st_name'))

# Returns true if object has attribute
print(hasattr(student,'st_age'))

# Set additional attribute st_marks
setattr(student,'st_marks','95')

# Get Attribute
print(getattr(student,'st_marks'))

# Checking for an attribute
print(hasattr(student,'demo'))

# Access methods using an object
st1 = student()
st1.demo()

輸出

Tim
True
95
True
Hello from demo() function

以上是如何在Python中找到物件的方法或屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除