Conditional statements in a class, but outside of

2019-06-16 04:51发布

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?

2条回答
劫难
2楼-- · 2019-06-16 05:37

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.

查看更多
在下西门庆
3楼-- · 2019-06-16 05:42

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.

查看更多
登录 后发表回答