Yug*_*amo 33 python oop class instance
我想理解__init__Python中构造函数的参数.
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()
Run Code Online (Sandbox Code Playgroud)
结果:3
我称之为getone()方法:
print myObj.getone()
Run Code Online (Sandbox Code Playgroud)
结果:错误'getone()'不带参数(1given).
所以我更换:
def getone():
return 1
Run Code Online (Sandbox Code Playgroud)
同
def getone(self):
return 1
Run Code Online (Sandbox Code Playgroud)
结果:1这没关系.
但getone()方法不需要参数.
我是否必须使用毫无意义的论点?
std*_*err 46
在Python中:
self参数.self)或class(cls)参数.__init__是一个特殊的函数,没有重写__new__它将始终被赋予类的实例作为它的第一个参数.
使用builtin 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()
Run Code Online (Sandbox Code Playgroud)
也就是说,我会尽量使用@classmethod/ @staticmethod谨慎.如果您发现自己创建的对象除了staticmethods之外什么都没有,那么更多的pythonic要做的就是创建一个相关函数的新模块.