python中的“self.data”用法

2024-04-20 01:17:40 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我有一个关于Python中属性用法的问题。我了解到,在函数定义中,我们可以为对象指定一些新属性,例如:self!然而,当我试图使用它时,我得到了一个错误,那就是。。。实例没有“data”属性

class Lazy:
    def __call__(self, num):
            if num is None:
                    return self.data
            # It changes the current object in-place,
            # by reassigning the self attribute.
            else:
                    self.data += num

这是我的小密码。 我是个新手。我搞不清出了什么事。 非常感谢你。


Tags: the对象实例函数self用法data属性
3条回答

您试图引用self.data,但未初始化/声明它。

class Lazy:
    def __init__(self, data=0):
        self.data = data #You are initializing data to 0 or a user specified value

    def __call__(self, num):
        if num is None:
            return self.data
            # It changes the current object in-place,
            # by reassigning the self attribute.
        else:
            self.data += num

您只分配self.data如果num is None,因此可能会在分配之前尝试访问它。为了防止这种情况,可以在构造函数中初始化它:

class Lazy:
    def __init__(self):
        self.data = 0

    def __call__(self, num):
        if num is None:
            return self.data
        else:
            self.data += num

以下是导致错误的事件序列:

  1. 创建类的新实例。此时,Python对self.data一无所知:

    lazy = Lazy()
    
  2. 你叫它通过None

    lazy(None)
    
  3. 现在,Python输入__call__,因为if条件的计算结果是True,所以它尝试返回self.data。等一下。。。它仍然不知道self.data是什么。。。所以它指出了一个错误。

为了防止这种情况发生,在尝试对属性的值执行操作(例如,从函数返回属性)之前,必须先分配属性。它不必在构造函数中:就在Python第一次尝试访问属性之前。对于任何变量都是这样,即以下情况是不可能的:

print(a) # How do you expect Python to know the value of a?
a = 5    # too late to assign it now...

为了修改self.data,必须首先使用类的特殊__init__方法初始化self.data属性。

从官方文件来看:

object.__init__(self[, ...])

Called when the instance is created. The arguments are those passed to the class constructor expression.

因此,可以将self.data设置为0,那么__call__方法应该按编写的那样工作。

class Lazy:
    def __init__(self):
        self.data = 0

    def __call__(self, num):
        if num is None:
            return self.data
        else:
            self.data += num

相关问题 更多 >