I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:
Say I have a class that is supposed to define Circles but lacks a body:
class Circle():
pass
Since I have not defined any attributes, how can I do this:
my_circle = Circle()
my_circle.radius = 12
The weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an undefined name error
. I do understand that via dynamic typing I just bind variables to objects whenever I want, but shouldn't an attribute radius
exist in the Circle
class to allow me to do this?
EDIT: Lots of wonderful information in your answers! Thank you everyone for all those fantastic answers! It's a pity I only get to mark one as an answer.
self.radius
at the__init__
aren't you doing exactly the same thing? – Liquidradius
attribute for classCircle()
. In my case I didn't create any attribute in the class body. – Blinnyself
is just a variable like any other. – Liquid__init__
attribute of a class which happens to be invoked after object construction. – Cesta__init__()
is called during this statement:my_circle = Circle()
not after it.radius
is assigned after the__init()__
method has been called and the object is already constructed. – Blinny__init__
is called beforeradius
is added in your example. But it is called after the object is created, and you can replace it at any time. The syntaxdef __init__(self, ...)
isn't a magic incantation. It simply defines a function which become an attribute of the class object and then is called after the object is created but before it is returned and stored inmy_circle
. – Cesta__init__
and__new__
. It is the__new__
method that is called to create a class's instance, whereas,__init__
method is used to initialize the instance after it has been created.. So, there is a difference between the two methods.. Also,__init__
method takes an argumentself
whereas__new__
does not. (You can think why?? Because an instance has not been created yet..) – Singer