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

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

    If you want to do just a little hacky thing do

    class A(object):
        ...
    some_func(A)
    

    If you want to do something more sophisticated you can use a metaclass. A metaclass is responsible for manipulating the class object before it gets fully created. A template would be:

    class AType(type):
        def __new__(meta, name, bases, dct):
            cls = super(AType, meta).__new__(meta, name, bases, dct)
            some_func(cls)
            return cls
    
    class A(object):
        __metaclass__ = AType
        ...
    

    type is the default metaclass. Instances of metaclasses are classes so __new__ returns a modified instance of (in this case) A.

    For more on metaclasses, see http://docs.python.org/reference/datamodel.html#customizing-class-creation.

提交回复
热议问题