gpt4 book ai didi

python - 鸭子在 python 中打洞

转载 作者:太空狗 更新时间:2023-10-30 01:24:12 25 4
gpt4 key购买 nike

我希望能够添加属性 http://docs.python.org/library/functions.html#property对象(类的特定实例)。这可能吗?

关于 python 中的 duck punching/monkey patching 的其他一些问题:

Adding a Method to an Existing Object Instance

Python: changing methods and attributes at runtime

更新:delnan 在评论中回答

Dynamically adding @property in python

最佳答案

以下代码有效:

#!/usr/bin/python

class C(object):
def __init__(self):
self._x = None

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

s = C()

s.x = "test"
C.y = property(C.getx, C.setx, C.delx, "Y property")
print s.y

但我不确定您是否应该这样做。

关于python - 鸭子在 python 中打洞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com