+ 1
Python: How can I fix this attribute error?
class zzz: def __init__(self,n): self.x = n def set_y(self): self.y=self.x * 2 obj = zzz(2) print(obj.x + obj.y)
3 Antworten
+ 5
you can add self.set_y() to the __init__ method:
def __init__(self,n):
self.x = n
self.set_y()
+ 4
self.y doesn't exist until you call obj.set_y().
obj = zzz(2)
obj.set_y()
print(obj.x + obj.y)
+ 3
Russ is right. Also, it's better to initialize that value in the __init__ method, some editors (like pycharm) will give you a warning for that