类方法中的 Python 关键字参数 [英] Python Keyword Arguments in Class Methods

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

问题描述

我正在尝试编写一个带有 3 个关键字参数的类方法.我以前使用过关键字参数,但似乎无法在我的班级中使用它.代码如下:

I'm attempting to write a class method that takes 3 keyword arguments. I've used keyword arguments before but can't seem to get it to work inside of my class. The following code:

def gamesplayed(self, team = None, startyear = self._firstseason,
                endyear = self._lastseason):

    totalGames = 0

    for i in self._seasons:
        if((i.getTeam() == team or team == "null") and
           i.getYear() >= startyear and i.getYear() <= endyear):

            totalGames += i .getGames()

    return totalGames

产生错误:

NameError: name 'self' 未定义

NameError: name 'self' is not defined

如果我去掉关键字参数并使它们成为简单的位置参数,它就可以正常工作.因此,我不确定我的问题出在哪里.在此先感谢您的帮助.

If I take out the keyword arguments and make them simple positional ones, it works fine. Therefore I am not sure where my problems lies. Thanks in advance for any help.

推荐答案

def gamesplayed(self, team = None, startyear = self._firstseason, endyear = self._lastseason):

在函数声明中,您尝试使用 self 引用实例变量.然而,这不起作用,因为 self 只是函数第一个参数的变量名,它获取对传入的当前实例的引用.因此,self 特别不是始终指向当前实例的关键字(与其他语言中的 this 不同).这也意味着该变量在函数声明期间尚未定义.

In the function declaration you are trying to reference instance variables using self. This however does not work as self is just a variable name for the first argument of the function which gets a reference to the current instance passed in. As such, self is especially not a keyword that always points to the current instance (unlike this in other languages). This also means that the variable is not yet defined during the declaration of the function.

您应该做的是简单地使用 None 预设这些参数,并在这种情况下在函数体内将它们预设为这些值.这还允许用户将值实际解析为导致默认值的方法,而无需从类中的某处实际访问这些值.

What you should do is to simply preset those parameters with None, and preset them to those values in that case inside the function body. This also allows users to actually parse a value to the method that results in the default values without having to actually access the values from somewhere inside your class.

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

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