简体   繁体   English

类方法中的 Python 关键字参数

[英]Python Keyword Arguments in Class Methods

I'm attempting to write a class method that takes 3 keyword arguments.我正在尝试编写一个带有 3 个关键字参数的类方法。 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

produces the error:产生错误:

NameError: name 'self' is not defined NameError: 名称 'self' 未定义

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

In the function declaration you are trying to reference instance variables using self .在函数声明中,您尝试使用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).作为然而,这并不工作, self仅仅是它获取到超过了当前实例的引用函数的第一个参数变量名。因此, self尤其不是关键字总是指向当前实例(不像this在其他语言)。 This also means that the variable is not yet defined during the declaration of the function.这也意味着在函数声明期间变量尚未定义。

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

Default values for keyword arguments are bound at module construction time, not at class instance construction time.关键字参数的默认值在模块构建时绑定,而不是在类实例构建时绑定。 This is why self is not defined in this context.这就是为什么在这个上下文中没有定义self

The same fact about default values can create all sorts of problems any time you want a keyword argument where the default value updates every time the function is called.关于默认值的相同事实可以在任何时候你想要一个关键字参数时产生各种各样的问题,每次调用函数时默认值都会更新。 When you run the program, you'll find that the default value you expect to be updating is always set to the value constructed when the module was first initialized.当您运行程序时,您会发现您希望更新的默认值始终设置为首次初始化模块时构造的值。

I would advise using None as a default keyword parameter in both instances, as poke and others have suggested.正如poke和其他人所建议的那样,我建议在这两种情况下都使用None作为默认关键字参数。 Your code could look something like:您的代码可能类似于:

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

You cannot refer to self like that.你不能这样称呼self I am not aware of a way to refer to self in a keyword argument's default value.我不知道在关键字参数的默认值中引用self的方法。 You can use a placeholder instead, and set the default in the function body.您可以改用占位符,并在函数体中设置默认值。

_placeholder = object()

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

    # normal code here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM