假设我有这样的代码:
class Num:
def __init__(self,num):
self.n = num
def getn(self):
return self.n
def getone():
return 1
myObj = Num(3)
print(myObj.getn()) # result: 3
但如果我尝试print(myObj.getone())
,我收到错误:'getone()' takes no arguments (1 given)
.
所以我替换:
def getone():
return 1
with
def getone(self):
return 1
Now print(myObj.getone())
shows 1
,正如预期的那样。但 -getone()
不需要任何参数就可以return 1
。我必须使用毫无意义的论证吗?
在Python中:
-
实例方法:要求
self
争论。
-
类方法:将类作为第一个参数。
-
静态方法:不需要实例(
self
)或类(cls
) 争论。
__init__
是一个特殊函数并且不能覆盖__new__
它将始终被赋予类的实例作为其第一个参数。
使用内置 classmethod 和 staticmethod 装饰器的示例:
import sys
class Num:
max = sys.maxint
def __init__(self,num):
self.n = num
def getn(self):
return self.n
@staticmethod
def getone():
return 1
@classmethod
def getmax(cls):
return cls.max
myObj = Num(3)
# with the appropriate decorator these should work fine
myObj.getone()
myObj.getmax()
myObj.getn()
也就是说,我会尝试使用@classmethod
/@staticmethod
节约地。如果您发现自己创建的对象只包含staticmethod
更Pythonic 的做法是创建一个相关函数的新模块。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)