Self-referencing inside class definition

后端 未结 1 353
情话喂你
情话喂你 2021-01-18 10:35

How do I reference class object inside class definition? Could you advice me how you would do it? Or more specifically how do you pass class object inside decorator of class

相关标签:
1条回答
  • 2021-01-18 11:11

    You cannot, because during class definition, the class does not yet exist.

    You can apply the decorator after the class has been created:

    class A():
        def f(self):
            return 2
    
        def w(self, f):
            return fr + 5 
    
    A.f = dec(A.w)(A.f.__func__)
    

    or you can swap the order of the two method definitions and refer to w as a local name still:

    class A():
        def w(self, f):
            return fr + 5 
    
        @dec(w)
        def f(self):
            return 2
    

    In both cases you are passing in a callable A.w that is not bound to an instance. No self will be passed in, so you need to add that yourself, in the decorator:

    def decorate(w):
        def _wrap(f):
            def _call(self, *args, **kwargs):
                return w(self, f(*args, **kwargs))
            def _call
        return _wrap
    

    If you didn't expect w to be bound (it acting as a static method instead), you could just use a normal function instead here.

    Generally speaking, creating a decorator to call another method on the same instance is somewhat pointless; why not just call w from within f, directly?

    class A():
        def f(self):
            return self.w(2)
    
        def w(self, f):
            return fr + 5 
    
    0 讨论(0)
提交回复
热议问题