Python 中的静态方法和实例方法
我可以将 Python 方法同时定义为静态方法和实例方法吗?像这样:
class C(object):
@staticmethod
def a(self, arg1):
if self:
blah
blah
这样我就可以用两者来调用它:
C.a(arg1)
C().a(arg1)
目的是能够运行两组逻辑。如果作为实例方法访问,它将利用实例变量并执行某些操作。如果作为静态方法访问,则无需。
Can I define a Python method to be both static and instance at the same time? Something like:
class C(object):
@staticmethod
def a(self, arg1):
if self:
blah
blah
So that I can call it with both:
C.a(arg1)
C().a(arg1)
The intent is to be able to run two sets of logics. If accessed as an instance method, it would make use of instance variables and do stuff. If access as a static method, it will do without.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
formencode 有一个
classinstancemethod
装饰器,它可以做你想要的事情。它要求该方法有 2 个参数(self
和cls
,其中之一可以根据调用上下文传递None
)Lifted来自
formencode/declarative.py
示例用法
formencode has a
classinstancemethod
decorator, which does what what you want. It requires the method to have 2 arguments (self
andcls
, one of them could get passedNone
depending on calling context)Lifted from
formencode/declarative.py
Sample usage
不。如果可以的话,在方法中
self
意味着什么?No. What would
self
mean inside the method, if you could do that?如果您删除
a()
的self
参数,您的代码将正常工作。当您使用C().a(arg1)
调用它时,该实例将被忽略。但您希望此方法既作为静态方法又作为接收实例的方法。你不能两全其美。
Your code will work if you remove the
self
parameter toa()
. When you call it withC().a(arg1)
the instance is ignored.But you want this method to work as both a static method and a method that receives an instance. You can't have it both ways.