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

后端 未结 13 1794
旧时难觅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 10:40

    Nope. It works in a function because the function contents are executed at call-time. But the class contents are executed at define-time, at which point the class doesn't exist yet.

    It's not normally a problem because you can hack further members into the class after defining it, so you can split up a class definition into multiple parts:

    class A(object):
        spam= 1
    
    some_func(A)
    
    A.eggs= 2
    
    def _A_scramble(self):
        self.spam=self.eggs= 0
    A.scramble= _A_scramble
    

    It is, however, pretty unusual to want to call a function on the class in the middle of its own definition. It's not clear what you're trying to do, but chances are you'd be better off with decorators (or the relatively new class decorators).

提交回复
热议问题