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

后端 未结 5 1268
忘了有多久
忘了有多久 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

    [edited: use attribute to be a more direct answer; see the helpful comment by John Fouhy]

    You can use a descriptor to do what you want:

    class cls_or_inst_method(object):
        def __init__(self, class_method, instance_method):
            self.class_method = class_method
            self.instance_method = instance_method
    
        def __get__(self, obj, objtype):
            if obj is None:
                return self.class_method
            else:
                return lambda: self.instance_method(obj)
    
    def my_class_method(baz):
        return baz + 1
    
    def my_instance_method(self):
        return self.baz * 2
    
    class Foo(object):
        baz = 10
        bar = cls_or_inst_method(my_class_method, my_instance_method)
    

    Using the above:

    >>> print Foo.bar(5)
    6
    >>> my_foo = Foo()
    >>> print my_foo.bar()
    20
    

提交回复
热议问题