3 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
在property從一類(lèi)訪(fǎng)問(wèn)時(shí)(即,當(dāng)描述符總是返回本身instance是None在它的__get__方法)。
如果這不是您想要的,則可以編寫(xiě)一個(gè)始終使用類(lèi)對(duì)象(owner)而不是實(shí)例的新描述符:
>>> class classproperty(object):
... def __init__(self, getter):
... self.getter= getter
... def __get__(self, instance, owner):
... return self.getter(owner)
...
>>> class Foo(object):
... x= 4
... @classproperty
... def number(cls):
... return cls.x
...
>>> Foo().number
4
>>> Foo.number
4

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
這將成為Foo.number一個(gè)只讀屬性:
class MetaFoo(type):
@property
def number(cls):
return cls.x
class Foo(object, metaclass=MetaFoo):
x = 4
print(Foo.number)
# 4
Foo.number = 6
# AttributeError: can't set attribute
說(shuō)明:使用@property時(shí)的通常情況如下:
class Foo(object):
@property
def number(self):
...
foo = Foo()
中定義的屬性Foo對(duì)其實(shí)例是只讀的。也就是說(shuō),foo.number = 6將引發(fā)一個(gè)AttributeError。
類(lèi)似地,如果要Foo.number提高,則AttributeError需要設(shè)置中定義的屬性type(Foo)。因此,需要一個(gè)元類(lèi)。
請(qǐng)注意,這種只讀性無(wú)法避免受到黑客的攻擊??梢酝ㄟ^(guò)更改Foo的類(lèi)使該屬性可寫(xiě):
class Base(type): pass
Foo.__class__ = Base
# makes Foo.number a normal class attribute
Foo.number = 6
print(Foo.number)
版畫(huà)
6
或者,如果您希望設(shè)置Foo.number可設(shè)置的屬性,
class WritableMetaFoo(type):
@property
def number(cls):
return cls.x
@number.setter
def number(cls, value):
cls.x = value
Foo.__class__ = WritableMetaFoo
# Now the assignment modifies `Foo.x`
Foo.number = 6
print(Foo.number)
也打印6。

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
我同意unubtu的回答;它似乎起作用,但是,它在Python 3上無(wú)法使用這種精確的語(yǔ)法(特別是我在努力使用Python 3.4)??雌饋?lái)這是在Python 3.4下必須形成模式才能使事情起作用的方式:
class MetaFoo(type):
@property
def number(cls):
return cls.x
class Foo(metaclass=MetaFoo):
x = 4
print(Foo.number)
# 4
Foo.number = 6
# AttributeError: can't set attribute
添加回答
舉報(bào)