Python Object-Oriented Python Inheritance Multiple Superclasses

Philip Schultz
Philip Schultz
11,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)
Philip Schultz
Philip Schultz
11,322 Points

I asked a different question on stackoverflow regarding this code for the project, and someone brought this question to my attention.

This is what he said.

"Which raises another point: What are those class attributes for? If you wanted them to provide default values, you've already got default values on the initializer parameters for that, so they're useless.

If you wanted them to provide values during initialization, then they're potentially wrong, so they're worse than useless. If you need to have a self.sneaky before calling Character.init, the way to do that is simple: just move self.sneaky = sneaky up before the super() call.

In fact, that's one of the strengths of Python's "explicit super" model. In some languages, like C++, constructors are always called automatically, whether from inside out or outside in. Python forcing you to do it explicitly is less convenient, and harder to get wrong—but it means you can choose to do your setup either before or after the base class gets its chance (or, of course, a little of each), which is sometimes useful."

Does he have a point?

Here is the full post - https://stackoverflow.com/questions/52013570/how-mro-super-works-in-python

2 Answers

Balazs Pukli
Balazs Pukli
46,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.

Iulia Maria Lungu
Iulia Maria Lungu
16,922 Points

Philip Schultz you made my day, man. I've upvoted you in SOF as well. THANKS