Duck typing and class methods (or, how to use a method from both a class and an instance?)

后端 未结 3 1326
后悔当初
后悔当初 2021-01-07 05:47

I have some code which I would like to pass instances or classes interchangeably. All I will do in that code is to call a method that I expect both classes and instances to

3条回答
  •  萌比男神i
    2021-01-07 06:13

    You could create an own method type with a specially crafted __get__() method.

    In this method, you could do something like this:

    class combimethod(object):
        def __init__(self, func):
            self._func = func
        def classmethod(self, func):
            self._classfunc = classmethod(func)
            return self
        def __get__(self, instance, owner):
            if instance is None:
                return self._classfunc.__get__(instance, owner)
            else:
                return self._func.__get__(instance, owner)
    
    class A(object):
        @combimethod
        def go(self):
            print "instance", self
        @go.classmethod
        def go(cls):
            print "class", cls
    
    a=A()
    print "i:",
    a.go()
    print "c:",
    A.go()
    

    NOTE: The above is not very thoroughly tested, but seems to work. Nevertheless, it should be seen as a kind of "solution-near pseudo-code", not as a solution. It should give you an idea how to achieve your goal.

提交回复
热议问题