We know that with notation:
class Foo(object):
a = 1
def __init__(self):
self.b = 2
def c(self):
print('c')
we can create static variable Foo.a
, 'normal' variable b
, which will be available after creating and instance of Foo
, and method c
Today I was really surprised, that I can use conditional statements in a class, but outside of scope of the function
class C():
if True:
a = 1
b = 2
Languages like C++/Java, taught me that legal notation is similar to:
class Name():
variable = <expression>
Could you describe other rules, which refer to this specific scope? How I should name this scope?
In java everything is
classes
andobject
,classes
are container but in python everything isobject
.Classes
are alsoobjects
. likefunctions(also objects)
so when you use conditional statement in function then python allows you to do same in Classes.like:-
is same
you can assign functions even to store in a variable like you do for classes
while in java you can't define function outside the classes.
The class body is just Python code. It has specific scope rules, but anything goes otherwise. This means you can create functions conditionally:
or pull methods from elsewhere:
etc.
The Python documentation for
class
definitions states:and
Note the usually in that text. Essentially, the class body is executed as a function would, and anything you put in the body namespace becomes an attribute on the class.
The *Naming and binding section then tells you:
so names you define in this block cannot be directly accessed in methods; you'd use
class.name
orself.name
instead.