Python 继承'int'的类获得奇数的类鬼变量赋值
因为没有更好的标题,这就是我目前得到的Python 继承'int'的类获得奇数的类鬼变量赋值,python,class,python-3.x,inheritance,Python,Class,Python 3.x,Inheritance,因为没有更好的标题,这就是我目前得到的 class cordinate(int): def __new__(self, *args, **kwargs): self.x = args[0] self.y = args[1] ## Try to get pixel [0,0] and see what it got: if self.x == 0 and self.y == 0: print('New
class cordinate(int):
def __new__(self, *args, **kwargs):
self.x = args[0]
self.y = args[1]
## Try to get pixel [0,0] and see what it got:
if self.x == 0 and self.y == 0:
print('New Here')
print(self.x, self.y, self.angle, self.distance_from_edge)
self.angle = 225
self.distance_from_edge = 13
args = [self.distance_from_edge,]
return super(cordinate, self).__new__(self, *args, **kwargs)
cordinates = [cordinate(0,0), cordinate(2,10), cordinate(3,8)]
正如预期的那样,此代码会引发错误:
New Here
Traceback (most recent call last):
File "test.py", line 17, in <module>
cordinates = [cordinate(0,0), cordinate(2,10), cordinate(3,8)]
File "test.py", line 9, in __new__
print(self.x, self.y, self.angle, self.distance_from_edge)
AttributeError: type object 'cordinate' has no attribute 'angle'
此代码将输出:
New Here
2 10 225 13
现在,我相信这有一个简单的解释,没有必要惊慌或开始相信鬼魂
但我一直在玩弄它,但弄不懂它的意思。这种行为的解释是什么?它有名字吗?为什么一个新创建的实例会有一个将要设置为2行的值
期望值:总是崩溃-因为我故意在顶部放置了一个未定义键的打印。Python:3.5.1(Windows 8)正如您从中看到的,
\uuuuu new\uuuuu
的第一个参数是类(通常cls
),而不是实例(通常self
)。因此,您在cordinate
类上设置类属性(请注意,这是一个输入错误,类名称应该是CamelCased
)而不是每个实例。只要对\uuuu new\uuu
的第一次调用成功,这些属性就会在类上为所有后续调用设置
如果要在\uuuuu new\uuuuuu
中设置实例属性,请在拥有实例后进行设置,例如:
\uuuu new\uuuu
的第一个参数是类(通常cls
),而不是实例(通常self
)。因此,只要第一次调用没有崩溃,这些属性就已经设置好了。@jornsharpe你在拉我的链子吗?哈哈。如果是这么简单的话,我将不得不重新评估我在创建时如何将x
和y
分配给这个类。出于兴趣,你使用\uuuuuuuuuu新的
而不是\uuuuuuu初始
有什么原因吗?@Holloway可能是因为它们是int
的子类,这是不可变的。@Holloway正如Jornsharpe所说,这是因为我正在子类化int
,我之所以使用它的真正原因是因为我认为这些特定的继承案例就是这样工作的。我不知道它们实际上是如何工作的:)你完全正确,感谢你用外行术语解释,也感谢你提供了一个指向文档的直接指针。简单但完全合格的答案!干杯
New Here
2 10 225 13
class Coordinate(int):
def __new__(cls, *args, **kwargs):
self = super(Coordinate, cls).__new__(cls, *args[2:], **kwargs)
# ^ or 'inst' or whatever you like
self.x, self.y = args[:2]
...
return self