簡體   English   中英

如何動態設置類的任意屬性?

[英]How to dynamically set arbitrary attributes for a class?

我試圖意識到這一點,只是看是否有可能:

下面是我當前的解決方案:

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

如何解決?

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 數據模型的文檔以了解更多詳細信息。

默認情況下,Python確實已將其內置到類和對象中。

您固定的示例是:

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)

注意:這些方法僅封裝了getattrsetattrdelattr內置delattr ,因此沒有太多收獲。

我是OP,我在python官方文檔上找到了一個示例,該示例可以執行我想要的python屬性

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM