A class method which behaves differently when called as an instance method?

后端 未结 5 1316
忘了有多久
忘了有多久 2021-02-01 17:17

I\'m wondering if it\'s possible to make a method which behaves differently when called as a class method than when called as an instance method.

For example, as a skill

5条回答
  •  花落未央
    2021-02-01 17:47

    Questionably useful Python hacks are my forte.

    from types import *
    
    class Foo(object):
        def __init__(self):
            self.bar = methodize(bar, self)
            self.baz = 999
    
        @classmethod
        def bar(cls, baz):
            return 2 * baz
    
    
    def methodize(func, instance):
        return MethodType(func, instance, instance.__class__)
    
    def bar(self):
        return 4*self.baz
    
    
    >>> Foo.bar(5)
    10
    >>> a=Foo()
    >>> a.bar()
    3996
    

提交回复
热议问题