如何在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 objectsst1 = student()st2 = student()# The getattr() is used hereprint ("Name = ",getattr(st1,'st_name'))print ("Age = ",getattr(st2,'st_age'))

输出

Name = AmitAge = 18

访问和设置类属性

示例

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

class student:   st_name ='Tim'   st_age ='18'   def demo(self):      print("Hello from demo() function")# The getattr() is used hereprint(getattr(student,'st_name'))# Returns true if object has attributeprint(hasattr(student,'st_age'))# Set additional attribute st_markssetattr(student,'st_marks','95')# Get Attributeprint(getattr(student,'st_marks'))# Checking for an attributeprint(hasattr(student,'demo'))

输出

TimTrue95True

访问方法

示例

在这个例子中,我们将学习如何访问方法 –

立即学习“Python免费学习笔记(深入)”;

class student:   st_name ='Tim'   st_age ='18'   def demo(self):      print("Hello from demo() function")# The getattr() is used hereprint(getattr(student,'st_name'))# Returns true if object has attributeprint(hasattr(student,'st_age'))# Set additional attribute st_markssetattr(student,'st_marks','95')# Get Attributeprint(getattr(student,'st_marks'))# Checking for an attributeprint(hasattr(student,'demo'))# Access methods using an objectst1 = student()st1.demo()

输出

TimTrue95TrueHello from demo() function

以上就是如何在Python中找到对象的方法或属性?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1342908.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 05:59:42
下一篇 2025年12月13日 05:59:56

相关推荐

发表回复

登录后才能评论
关注微信