Hans Hans - 4 months ago 7
Python Question

Why Does This Usage of a Class Work in Python?

I run the following very trivial Python code. I am very surprised that it actually run. Could someone explain to me why I can even assign values to "nd" and "hel" without defining them in the class definition? Is this because the attribute can be added in the instance level?

class tempClass(object):

a = tempClass()
a.nd = 1
a.hel = 'wem3'

Answer

Python has no notion of variable declaration, only assignments. The same applies to attributes: you simply assign an initial value to bring it into existence.

There is nothing special about the __init__ method in this regard. For example,

class TempClass(object):
    def __init__(self):
        self.nd = 1

a = tempClass()
a.hel = 'wem3'

Both attributes are created in the same way: by assigning a value to them. __init__ is called when a is first created, but otherwise is not special. self inside __init__ is a reference to the object referenced by a, so self.nd = 1 is identical to a.nd = 1. After the object is created, a.hel is created and initialized with 'wem3' by the same process.