How to make super() work by manually filling the __class__ cell?

前端 未结 3 904
挽巷
挽巷 2020-12-29 10:30

In Python 3 one can use super() instead of super(MyClass, self), but this only works in methods that were defined inside the class. As described in

3条回答
  •  甜味超标
    2020-12-29 11:10

    You can use the function's dictionary.

    def f(self):
        super(f.owner_cls, self).f()
        print("B")
    
    def add_to_class(cls, member, name=None):
        if hasattr(member, 'owner_cls'):
            raise ValueError("%r already added to class %r" % (member, member.owner_cls))
        member.owner_cls = cls
        if name is None:
            name = member.__name__
        setattr(cls, name, member)
    
    class A:
         def f(self):
             print("A")
    
    class B(A):
         pass
    
    add_to_class(B, f)
    
    B().f()
    

    You can even add another attribute member_name if you don't want to hardcode the name of the name of the member inside the function.

提交回复
热议问题