Python 如何找到对象的方法或属性

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程