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

后端 未结 13 1771
旧时难觅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

    It's ok to reference the name of the class inside its body (like inside method definitions) if it's actually in scope... Which it will be if it's defined at top level. (In other cases probably not, due to Python scoping quirks!).

    For on illustration of the scoping gotcha, try to instantiate Foo:

    class Foo(object):
        class Bar(object):
            def __init__(self):
                self.baz = Bar.baz
            baz = 15
        def __init__(self):
            self.bar = Foo.Bar()
    

    (It's going to complain about the global name 'Bar' not being defined.)


    Also, something tells me you may want to look into class methods: docs on the classmethod function (to be used as a decorator), a relevant SO question. Edit: Ok, so this suggestion may not be appropriate at all... It's just that the first thing I thought about when reading your question was stuff like alternative constructors etc. If something simpler suits your needs, steer clear of @classmethod weirdness. :-)

提交回复
热议问题