方法可以用作静态方法或实例方法吗?
我希望能够做到这一点:
class A(object):
@staticandinstancemethod
def B(self=None, x, y):
print self is None and "static" or "instance"
A.B(1,2)
A().B(1,2)
这似乎是一个应该有一个简单解决方案的问题,但我想不出或找不到一个。
I'd like to be able to do this:
class A(object):
@staticandinstancemethod
def B(self=None, x, y):
print self is None and "static" or "instance"
A.B(1,2)
A().B(1,2)
This seems like a problem that should have a simple solution, but I can't think of or find one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是可能的,但请不要这样做。但我还是忍不住实现了它:
...以及它的用途:
邪恶!
It is possible, but please don't. I couldn't help but implement it though:
...and its use:
Evil!
由于无论如何您都希望使用静态方法来创建新类,因此最好将其设为普通方法并在 __init__ 方法末尾调用它。
或者,如果您不希望这样做,请在类外部创建一个单独的工厂函数,该函数将实例化一个新的空对象,并在其上调用所需的方法。
可能有一些方法可以完全满足您的要求,但它们会在 Python 的内部机制中徘徊,令人困惑,并且在 python 2.x 和 3.x 之间不兼容 - 而且我看不出真正需要它。
Since you'd like the static method case to be used to create a new class anyway, you'd best just make it a normal method and call it at the end of the
__init__
method.Or, if you don't want that, create a separate factory function outside the class that will instantiate a new, empty object, and call the desired method on it.
There probably are ways of making exactly what you are asking for, but they will wander through the inner mechanisms of Python, be confusing, incompatible across python 2.x and 3.x - and I can't see a real need for it.
从您所说的来看,这符合您要寻找的内容吗?
我不确定是否有一种方法可以完全执行您所说的“内置”操作
From what you're saying, is this along the line of what you're looking for?
I'm not sure there is a way to do exactly what you're saying that is "built in"
您的问题的答案是不,您不能这样做。
因为Python也支持常规函数,所以我要做的是在该类之外定义一个函数,然后从常规方法调用该函数。呼叫者可以决定需要哪一个。
The answer to your question is no, you can't do that.
What I would do, since Python also supports regular functions, is define a function outside that class, then call that function from a normal method. The caller can decide what which one is needed.