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

泪湿孤枕 提交于 2019-12-05 02:23:32

The class body is just Python code. It has specific scope rules, but anything goes otherwise. This means you can create functions conditionally:

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

or pull methods from elsewhere:

import some_module

class D:
    method_name = some_module.function_that_accepts_self

etc.

The Python documentation for class definitions states:

A class definition is an executable statement.

and

The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

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:

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods

so names you define in this block cannot be directly accessed in methods; you'd use class.name or self.name instead.

In java everything is classes and object, classes are container but in python everything is object. Classes are also objects. like functions(also objects) so when you use conditional statement in function then python allows you to do same in Classes.

like:-

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

is same

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

you can assign functions even to store in a variable like you do for classes

def A():
    pass

a = A # is valid

while in java you can't define function outside the classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!