鸭子在 python 中打孔属性

发布于 2024-10-26 19:12:06 字数 630 浏览 11 评论 0原文

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

关于 python 中的鸭子打孔/猴子修补的其他一些问题:

向现有的方法添加方法对象实例

Python:在运行时更改方法和属性

更新:delnan 在评论中回答

在 python 中动态添加 @property

I'd like to be able to add a property http://docs.python.org/library/functions.html#property to an object (a specific instance of a class). Is this possible?

Some other questions about duck punching/monkey patching in python:

Adding a Method to an Existing Object Instance

Python: changing methods and attributes at runtime

UPDATE: Answered by delnan in the comments

Dynamically adding @property in python

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一个人练习一个人 2024-11-02 19:12:06

以下代码有效:

#!/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

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

Following code works :

#!/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

But I am not sure you should be doing it.

谜兔 2024-11-02 19:12:06
class A:
    def __init__(self):
       self.a=10

a=A()
print a.__dict__
b=A()
setattr(b,"new_a",100)
print b.__dict__

希望这能解决您的问题。

a.__dict__  #{'a': 10}
b.__dict__  #{'a': 10, 'new_a': 100}
class A:
    def __init__(self):
       self.a=10

a=A()
print a.__dict__
b=A()
setattr(b,"new_a",100)
print b.__dict__

Hope this solves your problem.

a.__dict__  #{'a': 10}
b.__dict__  #{'a': 10, 'new_a': 100}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文