__Python中的init和参数

2024-05-23 17:08:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想了解Python中构造函数__init__的参数。

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()

结果:3

我调用getone()方法:

print myObj.getone()

结果:错误“getone()”不接受参数(1给定)。

所以我替换:

def getone():
    return 1

def getone(self):
    return 1

结果:1这没问题。

但是getone()方法不需要参数。

我必须用无意义的论点吗?


Tags: 方法self参数returninitdef错误num
3条回答

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

Read more about classes in Python

在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。如果您发现自己创建的对象只由staticmethods组成,那么要做的更像是创建一个新的相关函数模块。

方法不使用self参数(它是对方法所附加实例的引用)并不意味着可以忽略它。它总是必须在那里,因为Python总是试图传递它。

相关问题 更多 >