+ 1

Error: self not found

So I tried this: class X: def __init__(self, y): self.y = y def setY(self, y=self.y): self.y = y My idea was to set a first value with the instantiation and have a setter to change it later. In case the user enters nothing, I wanted to keep the original value. Now why is this not working?

20th Oct 2018, 6:42 PM
HonFu
HonFu - avatar
4 Réponses
+ 5
HonFu Maybe this will help: https://stackoverflow.com/a/5555470 "It doesn't work because default arguments are evaluated at function definition time, not at call time" also here: https://stackoverflow.com/a/8131960 "You can't really define this as the default value, since the default value is evaluated when the method is defined which is before any instances exist."
20th Oct 2018, 8:03 PM
Burey
Burey - avatar
+ 5
self is not recognized as a parameter Try setting default value of None and inside the setter you can use "or" to go to the default value if y is None class X: def __init__(self, y): self.y = y def setY(self, y=None): self.y = y or self.y x = X(42) print(x.y) x.setY() print(x.y)
20th Oct 2018, 7:12 PM
Burey
Burey - avatar
+ 1
Burey hm, okay, interesting. I had seen something like that behaviour in functions but never really understood it. Not sure if I do now, but at least it's consistent, that already helps a lot. Thank you!
20th Oct 2018, 9:38 PM
HonFu
HonFu - avatar
0
Burey, that definitely works, but I am wondering why this even gives an error, I find it surprising. In other areas, like in the or-part of a boolean or an else that never happens, it has no effect to write an unknown name (since depending on the program flow it might later be known). Since I will later instantiate my object and deliver a self.y, shouldn't the class (logically) be lenient and allow it?
20th Oct 2018, 7:35 PM
HonFu
HonFu - avatar