0

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'
Hans
  • 1,269
  • 3
  • 19
  • 38
  • 1
    The way that objects were designed allows you to create attributes by assignment. Try the same thing with a function (functions are objects): define a function, ```f```, then add an attribute to it - ```f.new = 1``` - it works :). ```...can be added in the instance level?``` attributes can be added to the class itself in the same manner. – wwii Aug 04 '16 at 04:14
  • Thank you, @wwii. Does it work adding a function, instead of an attribute, to an instance of a class? I tried it. It did not work. But maybe I did not do it the right way. – Hans Aug 04 '16 at 04:20
  • Define the function then assign the function name to the class or instance attribute. ```def f(): print('1'); tempClass.foo = f```. – wwii Aug 04 '16 at 04:27
  • 1
    So I played around a bit and some objects don't allow that behaviour but classes and functions do. There is a hint in the "User-defined functions" section of [3.2 The standard type hierarchy](https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy) in the docs. – wwii Aug 04 '16 at 04:31
  • Thank you, @wwii. It works as you said. – Hans Aug 04 '16 at 04:37
  • The exact code pasted would not run at all, it has a basic syntax error. – Burhan Khalid Aug 04 '16 at 04:46
  • @wwii see [this link](http://stackoverflow.com/questions/1529002/cant-set-attributes-of-object-class) to a SO question about why you can't assign to built-in types. – juanpa.arrivillaga Aug 04 '16 at 04:47

1 Answers1

2

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.

chepner
  • 497,756
  • 71
  • 530
  • 681