鸭子在python中的一个属性中打孔 [英] Duck punching in a property in python

查看:60
本文介绍了鸭子在python中的一个属性中打孔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够添加一个属性 http://docs.python.org/library/functions.html#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?

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

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

向现有对象实例添加方法

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

更新:由 delnan 在评论中回答

UPDATE: Answered by delnan in the comments

在python中动态添加@property

推荐答案

以下代码有效:

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

这篇关于鸭子在python中的一个属性中打孔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆