+ 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)

16th Sep 2020, 7:39 PM
Solus
Solus - avatar
3 ответов
+ 5
you can add self.set_y() to the __init__ method: def __init__(self,n): self.x = n self.set_y()
16th Sep 2020, 8:06 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 4
self.y doesn't exist until you call obj.set_y(). obj = zzz(2) obj.set_y() print(obj.x + obj.y)
16th Sep 2020, 7:46 PM
Russ
Russ - avatar
+ 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
16th Sep 2020, 7:49 PM
Bagon
Bagon - avatar