The same method for class and instance

后端 未结 3 863
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    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

     asdf
    <__main__.Books object at 0xb7696dec> asdf
    

提交回复
热议问题