python getattr setattr

本文详细介绍了Python中getattr和setattr方法的使用,通过实例展示了如何获取类属性及动态修改类属性,提供了清晰易懂的代码示例。

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

getattr用来获取某个类中的变量或函数
setattr则可以动态修改、增加某个类的变量或函数
代码一目了然

Python 2.7.10 (default, Sep 14 2015, 02:26:06) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class test(object):
...     def __init__(self):
...             self.attr1 = "attr_1"
...             self.attr2 = "attr_2"
...     def method1(self, output):
...             print output
... 
>>> t = test()
>>> print getattr(t, "attr1")
attr_1
>>> print getattr(t, "attr2")
attr_2
>>> print getattr(t, "attr3")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'test' object has no attribute 'attr3'
>>> print getattr(t, "method1")
<bound method test.method1 of <__main__.test object at 0x10ceae510>>
>>> b = getattr(t, "method1")
>>> b("fuck")
fuck
>>> setattr(t, "attr3", "attr_3")
>>> getattr(t, "attr3")
'attr_3'
>>> getattr(t, "attr4")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'test' object has no attribute 'attr4'
>>> getattr(t, "attr4", "default_attr4")
'default_attr4'
>>> setattr(t, "method2", t.method1)
>>> b = getattr(t, "method2")
>>> b("fuck")
fuck
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值