传递self.var(实例属性)作为默认方法参数 [英] Passing self.var (instance attribute) as default method parameter

查看:113
本文介绍了传递self.var(实例属性)作为默认方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数 fiz 中分配 num1 = self.var1 时,Python表示未解析的引用。为什么呢?

While assigning num1 = self.var1 in function fiz, Python says unresolved reference. Why is that?

class Foo:

    def __init__(self):
        self.var1 = "xyz"

    def fiz(self, num1=self.var1):
        return


推荐答案

在定义方法时,方法(和函数)的默认参数值会被解析 。当这些值是可变的时候,这会导致一个普通的Python getcha:Least Astonishment在Python中:可变默认参数

Method (and function) default parameter values are resolved when the method is defined. This leads to a common Python gotcha when those values are mutable: "Least Astonishment" in Python: The Mutable Default Argument

在您的情况下,没有 self 方法被定义(如果在范围中有这样的名称,因为你还没有实际完成类 Foo 的定义,它不会是 Foo instance!)你不能在定义中通过名称引用 class 引用 Foo 也会导致 NameError 我可以使用类属性作为实例方法的默认值吗?

In your case, there is no self available when the method is defined (and if there was such a name in scope, as you haven't actually finished defining the class Foo yet, it wouldn't be a Foo instance!) You can't refer to the class by name inside the definition either; referring to Foo would also cause a NameError: Can I use a class attribute as a default value for an instance method?

但是,通常的方法是使用作为占位符,然后在方法体内分配默认值:

Instead, the common approach is to use None as a placeholder, then assign the default value inside the method body:

def fiz(self, num1=None):
    if num1 is None:
        num1 = self.val1
    ...

这篇关于传递self.var(实例属性)作为默认方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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