Python 数据描述符不能用作实例变量?
Python data descriptor did not work as instance variable?
正如官方demo描述的那样here,下面的代码会打印Retrieving var "x"
.
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating', self.name
self.val = val
class MyClass1(object):
x = RevealAccess(10, 'var "x"')
MyClass1().x
但是如果x
是一个实例变量,数据描述符机制将不起作用,下面的代码不会打印任何东西。
class MyClass2(object):
def __init__(self):
self.x = RevealAccess(10, 'var "x"')
MyClass2().x
并且,如果我按照 here 所述手动实施数据描述符机制,以下代码将再次 Retrieving var "x"
。
class MyClass3(object):
def __init__(self):
self.x = RevealAccess(10, 'var "x"')
def __getattribute__(self, key):
"Emulate type_getattro() in Objects/typeobject.c"
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v
MyClass3().x
那么,默认的数据描述符机制是否没有像文档中描述的那样实现?
我正在使用 python 2.7.10.
这里描述的操作方法是错误的。 Python data model 的描述正确:
The following methods [__get__
, __set__
, and __delete__
] only apply when an instance of the class
containing the method (a so-called descriptor class) appears in an
owner class (the descriptor must be in either the owner’s class
dictionary or in the class dictionary for one of its parents).
描述符必须是 class 个属性。
正如官方demo描述的那样here,下面的代码会打印Retrieving var "x"
.
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating', self.name
self.val = val
class MyClass1(object):
x = RevealAccess(10, 'var "x"')
MyClass1().x
但是如果x
是一个实例变量,数据描述符机制将不起作用,下面的代码不会打印任何东西。
class MyClass2(object):
def __init__(self):
self.x = RevealAccess(10, 'var "x"')
MyClass2().x
并且,如果我按照 here 所述手动实施数据描述符机制,以下代码将再次 Retrieving var "x"
。
class MyClass3(object):
def __init__(self):
self.x = RevealAccess(10, 'var "x"')
def __getattribute__(self, key):
"Emulate type_getattro() in Objects/typeobject.c"
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v
MyClass3().x
那么,默认的数据描述符机制是否没有像文档中描述的那样实现?
我正在使用 python 2.7.10.
这里描述的操作方法是错误的。 Python data model 的描述正确:
The following methods [
__get__
,__set__
, and__delete__
] only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).
描述符必须是 class 个属性。