Conditional statements in the class, but outside the scope of the function

We know that with the notation:

class Foo(object): a = 1 def __init__(self): self.b = 2 def c(self): print('c') 

we can create a static variable Foo.a , 'normal' variable b , which will be available after creating and instantiating Foo , and the method c

Today I was very surprised that I can use conditional operators in the class, but outside the scope of the function

 class C(): if True: a = 1 b = 2 

Languages ​​such as C ++ / Java taught me that legal notation is similar to:

 class Name(): variable = <expression> 

Could you describe other rules that apply to this particular area? What should I call this area?

+9
scope python class conditional-statements
source share
2 answers

The body of the class is just Python code. It has specific area rules, but everything goes differently. This means that you can create functions conditionally:

 class C: if some_condition: def optional_method(self): pass 

or get methods from other sources:

 import some_module class D: method_name = some_module.function_that_accepts_self 

etc.

The Python documentation for class definitions reads:

A class definition is an executable statement.

and

The classs set is then executed in a new execution frame (see Naming and Binding ) using the newly created local namespace and the original global namespace. (Typically, a set contains only function definitions.) When the classs set finishes executing, its execution frame is discarded, but its local namespace is preserved. Then, a class object is created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

Pay attention usually to this text. In fact, the body of the class is executed as a function, and everything that you put in the namespace of the body becomes an attribute of the class.

In the Names and Bindings section, you are informed:

The scope of names defined in a class block is limited to a class block; this does not apply to method code blocks

therefore, the names that you define in this block cannot be directly accessed in methods; instead, you would use class.name or self.name .

+12
source share

In java all classes and object , classes are container, but in python all object . classes also objects . e.g. functions(also objects) , so when you use a conditional operator in a function, then python allows you to do the same in classes.

as: -

 def A(): if condition: do something elif condition: do somethig else: do something 

same

 Class A() if condition: do something elif condition: do somethig else: do something 

you can even assign functions to be stored in a variable, as is done for classes

 def A(): pass a = A # is valid 

and in java you cannot define a function outside of classes.

+1
source share

All Articles