如何在 Python 中动态访问类属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2425272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically access class properties in Python?
提问by Honza Pokorny
Let's say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:
假设我创建了一个类的实例,并希望为其公共属性分配一些值。通常,这将是这样完成的:
class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
But, what if a write a function that takes a class as parameter and I would like to assign some values to the public properties of that class dynamically - that is via variables and loops (without knowing how many there are or what they are called.)
但是,如果编写一个将类作为参数的函数,并且我想动态地为该类的公共属性分配一些值 - 即通过变量和循环(不知道有多少或它们被调用)怎么办。 )
The obvious would be:
显而易见的是:
myclass = MyClass()
myclass['name'] = "My name"
But that doesn't work.
但这不起作用。
Any ideas?
有任何想法吗?
回答by shylent
setattr(my_class_instance, 'attr_name', attr_value)
回答by r2rien
After reading rejected Syntax For Dynamic Attribute AccessI'm using a mixin class providing dictionary-style access to an object's attributes :
在阅读了被拒绝的动态属性访问语法后,我使用了一个 mixin 类,该类提供对对象属性的字典式访问:
class MyClass:
def __init__(self):
self.name = None
self.text = None
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
return setattr(self, name, value)
def __delitem__(self, name):
return delattr(self, name)
def __contains__(self, name):
return hasattr(self, name)
While still being able to set attributes directly:
虽然仍然可以直接设置属性:
myclass = MyClass()
myclass.name = "foo"
myclass.text = "bar"
it's then possible to set them dynamically :
然后可以动态设置它们:
for attr in ('name', 'text'):
myclass[attr] = confirm(attr, default=myclass[attr])
回答by Pratik Deoghare
Using dir
with setattr
should do the job
使用dir
with setattr
应该可以完成这项工作
class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
for prop in dir(myclass):
print '%s:%s'%(prop,getattr(myclass,prop))
print
for prop in dir(myclass):
if prop[:2]!='__' and prop[-2:]!='__':
print prop[-2:]
setattr(myclass,prop,"Foo Bar")
for prop in dir(myclass):
print '%s:%s'%(prop,getattr(myclass,prop))
But be careful because this code also sets '__doc__', '__init__', '__module__'
properties to "Foo Bar". So you will have to take care of avoiding certain things given to you by dir
(especially those which start and end with __
double underscores).
但要小心,因为此代码还将'__doc__', '__init__', '__module__'
属性设置为“Foo Bar”。所以你必须注意避免某些东西给你dir
(尤其是那些以__
双下划线开头和结尾的东西)。