使用 __init__ 和设置类变量之间的区别
我正在尝试学习描述符,但我对对象行为感到困惑 - 在下面的两个示例中,据我了解 __init__ 它们应该工作相同。 有人可以解开我的困惑,或者向我指出可以解释这一点的资源吗?
import math
class poweroftwo(object):
"""any time this is set with an int, turns it's value to a tuple of the int
and the int^2"""
def __init__(self, value=None, name="var"):
self.val = (value, math.pow(value, 2))
self.name = name
def __set__(self, obj, val):
print "SET"
self.val = (val, math.pow(val, 2))
def __get__(self, obj, objecttype):
print "GET"
return self.val
class powoftwotest(object):
def __init__(self, value):
self.x = poweroftwo(value)
class powoftwotest_two(object):
x = poweroftwo(10)
>>> a = powoftwotest_two()
>>> b = powoftwotest(10)
>>> a.x == b.x
>>> GET
>>> False #Why not true? shouldn't both a.x and b.x be instances of poweroftwo with the same values?
I'm trying to learn descriptors, and I'm confused by objects behaviour - in the two examples below, as I understood __init__
they should work the same. Can someone unconfuse me, or point me to a resource that explains this?
import math
class poweroftwo(object):
"""any time this is set with an int, turns it's value to a tuple of the int
and the int^2"""
def __init__(self, value=None, name="var"):
self.val = (value, math.pow(value, 2))
self.name = name
def __set__(self, obj, val):
print "SET"
self.val = (val, math.pow(val, 2))
def __get__(self, obj, objecttype):
print "GET"
return self.val
class powoftwotest(object):
def __init__(self, value):
self.x = poweroftwo(value)
class powoftwotest_two(object):
x = poweroftwo(10)
>>> a = powoftwotest_two()
>>> b = powoftwotest(10)
>>> a.x == b.x
>>> GET
>>> False #Why not true? shouldn't both a.x and b.x be instances of poweroftwo with the same values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请使用LeadingUpperCaseNames 命名所有类。
ax
是实例级访问,支持描述符。 这就是3.4.2.2节中“(所谓的描述符类)出现在另一个新式类的类字典中”的含义。 类字典必须由实例访问才能使用 __get__ 和 __set__ 方法。bx
是类级别的访问,不支持描述符。First, please name all classes with LeadingUpperCaseNames.
a.x
is instance-level access, which supports descriptors. This is what is meant in section 3.4.2.2 by "(a so-called descriptor class) appears in the class dictionary of another new-style class". The class dictionary must be accessed by an instance to use the__get__
and__set__
methods.b.x
is class-level access, which does not support descriptors.