Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Class Inheritance, __init__ and cls

The desired output of the code is that I have a class variable Team.stuff which has one entry holding the b instance, and the Player.stuff variable should be empty. Instead I get an error...

class Player:
  stuff=[]
  def __init__(self):
    cls.stuff.append(self)

class Team(Player):
  def __init__(self):
    super(Team, self).__init__()

b=Team()

ERROR

cls.stuff.append(self)
NameError: global name 'cls' is not defined

I could pass the cls variable in the Team.__init__(), but I'm not sure if that is the "correct" way, and more importantly the Player.__init__() would need a class variable, and I'm not sure on the syntax on how to do that.

like image 584
appleLover Avatar asked Jul 30 '26 13:07

appleLover


2 Answers

The reason for this is that cls in your __init__ function is not defined. The argument names self and cls are just naming conventions. In reality, you could name them foo and bar for an instance and a class method respectively, and foo would point at the class instance whilst bar would point a the class itself.

Moreover, self.stuff would be valid as when searching for an attribute, if an object does not have an attribute of such name in it's __dict__ dictionary, the __dict__ of it's class is looked instead. If both are missing, further lookups are done according to mro order.

Notice that, once you set an attribute stuff on an object instance, it will shadow the class definition.

Explained by example:

class MyClassA(object):
    stuff = []

class MyClassB(MyClassA):
     def __init__(foobar):
         # `foobar` points at the instance of `MyClassB` class.

         # MyClassA.stuff gets `1` object appended to it.
         foobar.stuff.append(1)

         # This should print '[1]'
         print foobar.stuff

         # `MyClassB` object gets a _new_ attribute named `stuff` pointing at a list.
         foobar.stuff = []

         # This should print '[]'.
         print foobar.stuff
like image 188
Maciej Gol Avatar answered Aug 01 '26 01:08

Maciej Gol


class Player(object):
    stuff=[]
    def __init__(self):
        self.stuff.append(self)

class Team(Player):
    def __init__(self):
        super(Team, self).__init__()

b = Team()
print(Team.stuff)

prints (something like)

[<__main__.Team object at 0xb7519dec>]
like image 35
unutbu Avatar answered Aug 01 '26 02:08

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!