类和实例的方法相同 [英] The same method for class and instance
问题描述
我有 Books
类和 select
方法.还有一个名为 book
的类的实例.我希望能够同时执行 Books.select(where='...')
和 book.select(where='...')
:>
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 Books.select(where='...')
and book.select(where='...')
:
class Books():
def select(obj, where):
print(obj, where)
book = Books()
Books.select(where='asdf')
book.select(where='asdf')
上面显然行不通,因为select
是一个实例绑定方法:
The above obviously doesn't work, because select
is an instance bound method:
Traceback (most recent call last):
File "test.py", line 7, in <module>
Books.select(where='asdf')
TypeError: select() takes exactly 2 arguments (1 given)
工作代码:
class Books():
@staticmethod
def select(obj, where):
print(obj, where)
book = Books()
Books.select(Books, where='asdf')
Books.select(book, where='asdf')
我得到:
vic@wic:~/projects/snippets$ python3 test.py
<class '__main__.Books'> asdf
<__main__.Books object at 0x17fd6d0> asdf
但我必须手动将类或其实例作为第一个参数传递给 select
方法 - 这不是我想要的.
But i have to manually pass the class or its instance as the first argument to the select
method - not what i want.
如果我让 select
成为一个类方法:
If i make select
a class method:
class Books():
@classmethod
def select(obj, where):
print(obj, where)
book = Books()
Books.select(where='asdf')
book.select(where='asdf')
我总是把一个类作为第一个参数:
I always get a class as the first argument:
vic@wic:~/projects/snippets$ python3 test.py
<class '__main__.Books'> asdf
<class '__main__.Books'> asdf
但我想在第二种情况下获得一个实例.
But i want to get an instance in the second case.
那么,有没有办法在不手动将类/实例作为第一个参数传递给静态方法的情况下完成我想要的?
So, is there a way to accomplish what i want without manually passing the class/instance as the first argument to a static method?
推荐答案
您可以使用 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')
收益
<class '__main__.Books'> asdf
<__main__.Books object at 0xb7696dec> asdf
这篇关于类和实例的方法相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!