Philip Schultz11,322 Points
Why are we assigning variables at the class level and in the init parameters?
Hello, I'm curious why we are assigning the same variable in two different spots. In the 'Agile' class he sets 'agile = True' at the class level and in the parameter of the init method. The same for the sneaky variable for the 'Sneaky' class. Aren't there any conflicts to be worried about? What is the advantage of setting it at both the class level and the instance level?
class Agile: agile = True def __init__(self, agile=True, *args, **kwargs): super().__init__(*args, **kwargs) self.agile = agile def evade(self): return self.agile and random.randint(0, 1)
Balazs Pukli46,047 Points
I think the most important thing to realise is that in not all programming languages brings the objects property to existence, if it is only declared in constructor functions. Originally, they must be declared on the class level, in order to be assigned by the constructor function.
In modern languages, it is a "syntactical sugar" that the object property is automatically created, if it is given value by the constructor function, but the inner workings are also similar: there is a property declared on the class, and that property is initiated/assigned by the constructor function - which is, of course, as it's name indicates, is called when a new object is constructed.