繁体   English   中英

类方法中的 Python 关键字参数

[英]Python Keyword Arguments in Class Methods

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

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: 名称 'self' 未定义

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

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

在函数声明中,您尝试使用self引用实例变量。 作为然而,这并不工作, self仅仅是它获取到超过了当前实例的引用函数的第一个参数变量名。因此, self尤其不是关键字总是指向当前实例(不像this在其他语言)。 这也意味着在函数声明期间变量尚未定义。

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

关键字参数的默认值在模块构建时绑定,而不是在类实例构建时绑定。 这就是为什么在这个上下文中没有定义self

关于默认值的相同事实可以在任何时候你想要一个关键字参数时产生各种各样的问题,每次调用函数时默认值都会更新。 当您运行程序时,您会发现您希望更新的默认值始终设置为首次初始化模块时构造的值。

正如poke和其他人所建议的那样,我建议在这两种情况下都使用None作为默认关键字参数。 您的代码可能类似于:

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

你不能这样称呼self 我不知道在关键字参数的默认值中引用self的方法。 您可以改用占位符,并在函数体中设置默认值。

_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