__init__和参数在Python [英] __init__ and arguments in Python

查看:96
本文介绍了__init__和参数在Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解在Python构造函数的参数 __ __的init

I want to understand arguments of the constructor __init__ in 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()

结果:3

我称之为 getone()方法:

print myObj.getone()

结果:错误'getone()不带任何参数(1given)

RESULT: Error 'getone()' takes no arguments (1given).

所以我代替:

def getone():
    return 1

def getone(self):
    return 1

结果:1​​,这是确定

RESULT:1 This is OK.

getone()方法需要任何参数。

我一定要使用无意义的说法?

Do I have to use meaningless argument?

推荐答案

Python的实例方法需要自我论证。类方法把类作为第一个参数。静态方法不需要任何实例()或类( CLS )的说法。

Python instance methods require the self argument. Class methods take the class as a first argument. Static methods do not require either the instance (self) or the class (cls) argument.

__的init __ 是一个特殊的功能,并没有覆盖 __新__ 它总是会给出类的实例,其第一个参数。

__init__ is a special function and without overriding __new__ it will always be given the instance of the class as its first argument.

使用内置类方法和静态方法装饰的一个例子:

An example using the builtin classmethod and staticmethod decorators:

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 谨慎。如果你发现自己创建包括什么,但静态方法对象S上更Python要做的是创建相关功能一个新的模块。

That said, I would try to use @classmethod/@staticmethod sparingly. If you find yourself creating objects that consist of nothing but staticmethods the more pythonic thing to do would be to create a new module of related functions.

这篇关于__init__和参数在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆