python: how to refer to the class from within it ( like the recursive function)

后端 未结 13 1841
旧时难觅i
旧时难觅i 2020-12-10 10:10

For a recursive function we can do:

def f(i):
  if i<0: return
  print i
  f(i-1)

f(10)

However is there a way to do the following thin

13条回答
  •  清歌不尽
    2020-12-10 11:01

    You can't with the specific syntax you're describing due to the time at which they are evaluated. The reason the example function given works is that the call to f(i-1) within the function body is because the name resolution of f is not performed until the function is actually called. At this point f exists within the scope of execution since the function has already been evaluated. In the case of the class example, the reference to the class name is looked up during while the class definition is still being evaluated. As such, it does not yet exist in the local scope.

    Alternatively, the desired behavior can be accomplished using a metaclass like such:

    class MetaA(type):
    
        def __init__(cls):
            some_func(cls)
    
    class A(object):
        __metaclass__=MetaA
      # do something
      # ...
    

    Using this approach you can perform arbitrary operations on the class object at the time that the class is evaluated.

提交回复
热议问题