5

我有一个 python 类的实例。

class Fum(object):
  foo = Foo()
  bar = Bar()

fum = Fum()

出于我不想进入的充分理由,我想修补这个对象,以便它的一个属性在某个用例中是禁止的。我希望如果我或其他开发人员尝试使用猴子修补对象上的属性,则会引发一个有用的异常来解释这种情况。我试图用一个属性来实现它,但没有运气。

例如,

def raiser():
  raise AttributeError("Don't use this attribute on this object. Its disabled for X reason.")

fum.bar = property(raiser)

>>> fum.bar
>>> <property object at 0xb0b8b33f>

我错过了什么?

4

1 回答 1

4

You cannot monkeypatch properties directly onto instances of an object. descriptors are a class-level concept and must be in an instance's class hierarchy. There is a trick that works, however:

class Fum(object):
    foo = Foo()
    bar = Bar()

fum = Fum()

class DerivedFum(fum.__class__):
    bar = property(raiser)

fum.__class__ = DerivedFum

fum.bar # --> raise AttributeError
于 2012-11-08T18:10:34.303 回答