__init__和Python中的参数

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参数.
  • 类方法:将类作为第一个参数.
  • 静态方法:不需要instance(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要做的就是创建一个相关函数的新模块.

  • 我认为你的答案有一些要点,值得一点点亮点.我希望你不介意改进:)!谢谢你的回答! (2认同)

Fel*_*ing 6

每个方法都需要接受一个参数:实例本身(如果是静态方法,则为类).

阅读有关Python类的更多信息.