The same method for class and instance

后端 未结 3 792
鱼传尺愫
鱼传尺愫 2020-12-17 05:51

I have class Books and method select in it. Also there is an instance of that class called book. I want to be able to do both Bo

相关标签:
3条回答
  • 2020-12-17 06:05

    You could use a descriptor:

    class Select(object):
        def __get__(self,obj,objtype):
            x=objtype if obj is None else obj
            def select(where):
                print(x,where)
            return select
    class Books(object):
        select=Select()
    
    book = Books()
    Books.select(where='asdf')
    book.select(where='asdf')
    

    yields

    <class '__main__.Books'> asdf
    <__main__.Books object at 0xb7696dec> asdf
    
    0 讨论(0)
  • 2020-12-17 06:12

    Solution using a descriptor and a decorator:

    class class_or_instance_method():
        def __init__(self, method):
            self.method = method
    
        def __get__(self, obj, objtype):
            x = obj or objtype
            def wrapped(*args, **kwargs):
                return self.method(x, *args, **kwargs)
            return wrapped        
    
    class Books():
        @class_or_instance_method
        def select(obj, where):
            print(obj, where)
    
    
    book = Books()
    Books.select(where='asdf')
    book.select(where='asdf')
    

    Result:

    <class '__main__.Books'> asdf
    <__main__.Books object at 0x2695890> asdf
    
    0 讨论(0)
  • 2020-12-17 06:14

    Just an example I founded on http://code.activestate.com/recipes/52304-static-methods-aka-class-methods-in-python/

    You create a little wrapper:

    class Callable:
        def __init__(self, anycallable):
            self.__call__ = anycallable
    

    And then defines your class and a class variable inside it.

    class Class2:
        def static2(name):
            print "Hi there",name
        static2 = Callable(static2)
    
    # now, a call such as:
    Class2.static2("Peter")
    # works just fine, and as-expected
    
    0 讨论(0)
提交回复
热议问题