gpt4 book ai didi

python - 使用 __init__ 和设置类变量之间的区别

转载 作者:行者123 更新时间:2023-11-28 16:55:06 24 4
gpt4 key购买 nike

我正在尝试学习描述符,但我对对象的行为感到困惑 - 在下面的两个示例中,据我了解 __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?

最佳答案

首先,请用 LeadingUpperCaseNames 命名所有类。

>>> a.x
GET
(10, 100.0)
>>> b.x
<__main__.poweroftwo object at 0x00C57D10>
>>> type(a.x)
GET
<type 'tuple'>
>>> type(b.x)
<class '__main__.poweroftwo'>

a.x 是实例级访问,支持描述符。这就是 3.4.2.2 节中“(一个所谓的描述符类)出现在另一个新式类的类字典中”的意思。实例必须访问类字典才能使用 __get____set__ 方法。

b.x是类级访问,不支持描述符。

关于python - 使用 __init__ 和设置类变量之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1018977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com