python方法和函数的解释_python中的内置函数getattr()介绍及示例

本文介绍了Python中内置函数getattr()的工作原理,它如何动态获取对象属性并演示了反射的应用。通过实例说明了如何在类中动态添加其他类的方法,展示了getattr()在解耦和效率提升方面的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在python的官方文档中:getattr()的解释如下:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

根据属性名称返回对象值。如果“name”是对对象属性的名称,则返回对应属性的值。

'# -*- coding: utf-8 -*-'

__author__ = 'lucas'

class attrtest(object):

def __init__(self):

pass

def trygetattr0(self):

self.name = 'lucas'

print self.name

#equals to self.name

print getattr(self,'name')

def attribute1(self,para1):

print 'attribute1 called and '+ para1+' is passed in as a parameter'

def trygetattr(self):

fun = getattr(self,'attribute1')

print type(fun)

fun('crown')

if __name__=='__main__':

test = attrtest()

print 'getattr(self,\'name\') equals to self.name '

test.trygetattr0()

print 'attribute1 is indirectly called by fun()'

test.trygetattr()

print 'attrribute1 is directly called'

test.attribute1('tomato')

这段代码执行的结果是:

getattr(self,'name') equals to self.name

lucas

lucas

attribute1 is indirectly called by fun()

attribute1 called and crown is passed in as a parameter

attrribute1 is directly called

attribute1 called and tomato is passed in as a parameter

Process finished with exit code 0

第一个函数tryattribute0()非常好理解,就如同定义里说的一样。第二个函数tryattribute1()就有一点费解了。其实原理并不复杂,我们看到fun的type是 instancemethod,这里你可以认为:对于函数,getattr()的返回值是一个指针,指针赋值给接受它的变量,以后call这个变量就等于调用变量指向的函数。

原理我们知道了,那getattr的作用是什么呢?

你熟悉java或者c#中的反射么?反射的一个重要作用就是延迟加载,这样可以解耦,这样可以让系统运行的更有效率。作为动态语言,python显然在这方面要更加强大,

getattr()就是实现python反射的一块积木,结合其它方法如setattr(),dir() 等,我们可以做出很多有趣的事情。

我们看以下场景:

1.我需要在一个类中动态添加其它类中有的方法:

#如果类A中有如下方法:

def addnewattributesfromotherclass(self,class_name):

func_names = dir(class_name)

for func_name in func_names:

if not func_name.startswith('_'):

new_func = getattr(class_name,func_name)

self.__setattr__(func_name,new_func())

我们只需要:

a = A()

b = B()

a.addnewattributesfromotherclass(b)

这样a就可以调用B中的'非私有'方法啦。

本文标题: python中的内置函数getattr()介绍及示例

本文地址: http://www.cppcns.com/jiaoben/python/110815.html

### Python 中 `__getattr__` 方法的用法 在 Python 的类定义中,`__getattr__` 是一种特殊的方法,用于处理访问不存在的属性的情况。当尝试访问对象的一个未定义属性时,如果该类实现了 `__getattr__` 方法,则会调用此方法来动态返回值或执行特定逻辑[^1]。 以下是关于 `__getattr__` 方法的一些重要特性使用场景: #### 特性描述 - 当通过点号操作符(`.`)访问一个实例的属性而找不到对应名称时,Python 会在抛出 `AttributeError` 前自动调用 `__getattr__` 方法。 - 需要注意的是,只有在常规属性查找失败的情况下才会触发 `__getattr__` 方法。因此,在类中显式定义的属性不会进入这个机制[^2]。 #### 使用示例 下面是一个简单的例子展示如何自定义行为以应对未知属性请求: ```python class DynamicAttributes: def __init__(self, initial=None): if initial is None: self.data = {} else: self.data = dict(initial) def __getattr__(self, name): """Called when an attribute lookup has not found the attribute in the usual places.""" try: return self.data[name] except KeyError as e: raise AttributeError(f"No such attribute: {e}") example = DynamicAttributes({"key": "value"}) print(example.key) # 输出 'value' # 下面这行将会引发 AttributeError 因为字典没有对应的键 # print(example.nonexistent_key) ``` 在这个例子中,我们创建了一个名为 `DynamicAttributes` 的类,它允许存储任意数量的关键字参数作为内部数据结构的一部分,并且可以通过普通的点记法访问这些关键字所代表的数据项。如果没有找到指定的名字,则会抛出异常表明缺少这样的特性[^3]。 另外需要注意一点区别:虽然两者都涉及到了获取成员的操作,但是 `__getattribute__` 函数几乎适用于所有的属性检索过程;相比之下,`__getattr__` 只有在标准途径无法定位到目标的时候才被激活[^4]。 #### 单例模式中的应用举例 有时可以利用 `__getattr__` 来辅助构建某些设计模式下的解决方案,比如单例模式。尽管这给出的例子主要依赖于装饰器完成任务,但我们同样能够借助类似的思路结合 `__getattr__` 达成目的[^5]: ```python class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance return cls._instances[cls] def __getattr__(cls, item): if hasattr(SingletonMeta._instances.get(cls), item): return getattr(SingletonMeta._instances.get(cls), item) raise AttributeError("No such attribute exists.") class MySingleton(metaclass=SingletonMeta): pass first_instance = MySingleton() second_instance = MySingleton() assert first_instance is second_instance ``` 在此案例中展示了另一种形式的单例实现方式——元编程技术。其中也体现了对于非正式存在的字段查询进行了重定向处理的方式[^6]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值