2014-07-18 27 views
1

我想实现这个只是为了看看,如果有可能:如何动态设置一个类的任意属性?

而下面是我目前的解决方案:

class A(object): 
    def fset(self, x, value): 
     self.__dict__.update({x:value}) 
    def fget(self, x): 
     return self.x 
    def fdel(self, x): 
     del self.x 

但它不完全,fget和FDEL功能不能很好地工作,例如

>>> a = A() 
>>> a.fset('z', 5) 
>>> a.z 
5 
>>> a.fget('z') 
'A' object has no attribute 'x' 
>>> a.fget(z) 
name 'z' is not defined 
>>> a.fdel(z) 
NameError: name 'z' is not defined 
>>> a.fdel('z') 
AttributeError: x 

如何解决?

回答

7

的Python已经这样做,通过自身:

>>> class A(object): 
    pass 

>>> a = A() 
>>> setattr(a, 'z', 5) 
>>> a.z 
5 
>>> getattr(a, 'z') 
5 
>>> delattr(a, 'z') 
>>> a.z 
AttributeError: 'A' object has no attribute 'z' 

阅读Python的data model的文档了解更多信息。

2

默认情况下,Python indeeed已经内置到类和对象中。

你举的例子是固定的:

class A(object): 

    def fset(self, x, value): 
     setattr(self, x, value) 

    def fget(self, x): 
     return getattr(self, x) 

    def fdel(self, x): 
     delattr(self, x) 

NB:没有很多通过这些方法来获得这种简单环绕着getattr,setattrdelattr builtins。

+0

其实那些内建自己只是包装该对象的'magic'__getattribute__','__setattr__'和'__delattr__'方法是自己的。它们可以被重写以实现自定义行为。 – jbaiter

+0

我不会去那么远,但是:) –

0

我的OP,我发现蟒蛇官方文档的例子,可以做我想做python properties

class C(object): 

    def getx(self): 
     return self._x 
    def setx(self, value): 
     self._x = value 
    def delx(self): 
     del self._x 
    x = property(getx, setx, delx, "I'm the 'x' property.") 

让我们来看看它的东西:

>>> c = C() 
>>> c.yyy = 123 
>>> c.yyy 
123 
>>> del c.yyy 
>>> c.yyy 
AttributeError: 'C' object has no attribute 'yyy'