首页 > 编程知识 正文

python hasattr函数,python getattr用法

时间:2023-05-04 11:26:32 阅读:160363 作者:4305

在Python中如何使用getattr ()函数

发布时间: 2020-08-12 14:57:55

来源:亿速云

阅读: 74

作者: brdmg

本文详细介绍了如何在Python中使用getattr () )函数。 编辑觉得很实用,所以分享一下仅供参考。 希望你能通过阅读这篇文章得到。

getatter ) )从方法名称字符串中调用方法。 这个方法最重要的作用是实现反射机制。 这意味着,通过以字符串形式检索方法的实例,可以将类可能调用的方法放置在性能分析中,然后根据需要动态加载。

可以从1:类中获取属性和函数

新的test.py文件,代码为以下:

# encoding:utf-8

导入系统

class GetText () :

def __init__(self ) :

通过

@staticmethod

def A () :

打印(thisisastaticmethodfunction ) )

默认(self ) :

打印(thisisafunc ) )

c='cc desc '

if __name__=='__main__':

打印(sys.modules [ _ _ name _ ] ) #

打印(gettext ) #

#获取函数

print(getattr(gettext,' a ' ) ) )

获取#函数返回值

getattr(gettext,' a ' ) ) # this is a staticmethod function

getattr(gettext ),' a ' ) ) # this is a staticmethod function

打印(getattr (gettext,' b ' ) ) )

#不允许使用非静态方法

#getattr(gettext,' b ' ) () ) ) ) ) ) ) ) ) ) )。

Getattr(Gettext ),' b ' ) ) # this is a func

print(getattr ) gettext,' c ' ) # cc desc

print(getattr(gettext ),' c ' ) ) # cc desc

从2:模块中获取类(从类名字符串中获取类对象) )。

新的test1.py,代码为以下:

#encoding:utf-8

导入系统

导入测试

打印(sys.modules (_ _ name _ ) )

#从模块中获取类对象

class_name=getattr(test,' GetText ' ) )。

打印(class _ name ) #

调用#类的属性和函数

print(getattr(class_name,' a ' ) ) )

获取#函数返回值

getattr(class_name,' a ' ) ) # this is a staticmethod function

getattr(class_name,' a ' ) ) # this is a staticmethod function

print(getattr(class_name ),' b ' ) )

#getattr(class_name,' b ' ) )不允许使用非静态方法

Getattr(class_name ),' b ' ) ) # this is a func

#获取属性值

print(getattr(class_name,' c ' ) ) # cc desc

print(getattr(class_name ),' c ' ) ) # cc desc

关于在Python中如何使用getattr () )函数,在这里进行了共享。 希望以上内容对大家有帮助。 我可以学到更多的东西。 如果你觉得文章好,你可以分享它给更多的人看。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。