请教: 如何使用getattr方法给变量的属性赋值

15 views
Skip to first unread message

前祁

unread,
Jan 2, 2010, 11:20:42 PM1/2/10
to pyth...@googlegroups.com
使用getattr可以很方便的取得某个对象引用的属性和方法。
但是如何使用这个方法修改属性的值呢?

如果有一个对象a, 有个属性b
使用 getattr(a,b) 就能够得到b的值

现在有办法通过getattr方法修改b的值吗?

王虎

unread,
Jan 2, 2010, 11:53:03 PM1/2/10
to pyth...@googlegroups.com
...
不是都拿到了么?直接赋值不久改变了啊?

>>> class A(object):
...     def __init__(self,):
...         self.val = 123
...
>>> a = A()
>>> getattr(a, 'val')
123
>>> a.val
123
>>> a.val = 456
>>> a.val
456
>>> setattr(a, 'val', 789)
>>> a.val
789
>>>

2010/1/3 前祁 <justrun19...@gmail.com>

--
来自: `python-cn`:CPyUG ~ 华蟒用户组 | 发言:pyth...@googlegroups.com
退订: http://tinyurl.com/45a9tb //针对163/qq邮箱:http://tinyurl.com/4dg6hc
详情: https://groups.google.com/group/python-cn
严正: 理解列表! 智慧提问! http://wiki.woodpecker.org.cn/moin/AskForHelp

前祁

unread,
Jan 3, 2010, 12:35:34 AM1/3/10
to pyth...@googlegroups.com
是的。谢谢。
忘掉了有setattr这个方法的,不好意思,问了个初级的问题。

2010/1/3 王虎 <ghost...@gmail.com>



--
Peter Qi, 祁前


技术总监  上海聚炎软件有限公司



电话 Tel: 86 21 6638-0361

手机 Mobile: 13482043258

电子邮件 Email: eplu...@gmail.com

地址: 上海市三泉路1858弄61号401室, 200449

Addr: 401, Building 61, sanquan Rd., Shanghai, P.R.China  200449

__________________________________________________________________________________
*声明*
本邮件及其所有附件均属机密信息,并且属于其拥有者、或者受到不得泄漏之保护。如您并非期待之收信者,请您电话或电邮通知其发信者,并从您的系统中删除本邮件及其所有附件;同时您不可以拷贝本邮件或其任何之附件,或将其内容披露至任何他人。如您因任何差错而收到此邮件,请您即刻通知发信人,并即刻删除本邮件及其所有附件。此致谢意。


*Notice*
This message and any attachment are confidential and may be privileged or otherwise protected from disclosure. If you are not the intended recipient, please telephone or email the sender and delete this message and any attachment from your system. If you are not the intended recipient you must not copy this message or any attachment or disclose the contents to any other person. If you have received this transmission in error, please notify the sender immediately and then delete all of it. Thank you.
Reply all
Reply to author
Forward
0 new messages