如何在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)

# 创建对象
st1 = student()
st2 = student()

# 这里使用了getattr()
print ("Name = ",getattr(st1,'st_name'))
print ("Age = ",getattr(st2,'st_age'))
Bash

输出

Name = Amit
Age = 18
Bash

访问并设置类属性

例子

在此示例中,要设置属性,我们将使用setattr()方法。

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

# 这里使用了getattr()
print(getattr(student,'st_name'))

# 如果对象具有属性则返回true
print(hasattr(student,'st_age'))

# 设置附加属性st_marks
setattr(student,'st_marks','95')

# 获取属性
print(getattr(student,'st_marks'))

# 检查属性
print(hasattr(student,'demo'))
Bash

输出

Tim
True
95
True
Bash

访问方法

例子

在此示例中,我们将学习如何访问方法 –

class 学生:
   st_name ='Tim'
   st_age ='18'
   def 演示(self):
      print("来自演示()函数的问候")

# 此处使用getattr()
print(getattr(学生,'st_name'))

# 如果对象有属性则返回true
print(hasattr(学生,'st_age'))

# 设置额外属性st_marks
setattr(学生,'st_marks','95')

# 获取属性
print(getattr(学生,'st_marks'))

# 检查属性
print(hasattr(学生,'演示'))

# 使用对象访问方法
st1 = 学生()
st1.演示()
Bash

输出

Tim
True
95
True
来自演示()函数的问候
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册