簡體   English   中英

AttributeError: 'myclass' object 沒有屬性 'x'

[英]AttributeError: 'myclass' object has no attribute 'x'

如果我有一個名為myclass的 class 定義如下

cl_test.py

class myclass():
    def fx1(self, a):
        x = a
        print(a)

    def fx2(self, b):
        c = self.x + b
        print(c)

我像這樣在另一個 Python 文件中調用這兩個函數

test.py

import cl_test

var = cl_test.myclass()

var.fx1(5)
var.fx2(3)

盡管 function fx1(5)被執行並打印5但是在執行第二個 function fx2(3)時,它會引發以下錯誤 -

c = self.x + b
AttributeError: 'myclass' object has no attribute 'x'

但是fx2(3)的預期 output 應該是8

我哪里錯了?

fx1中,變量x是方法的本地變量,您可以將其分配為self的屬性

def fx1(self, a):
    self.x = a
    print(a)

但是,您也可以在__init__中初始化此屬性,因為如果沒有,如果在沒有fx1的情況下調用fx2會出現同樣的錯誤,因為您從未分配過x ,以下代碼允許使用初始值var = cl_test.myclass(2)或沒有,它將是 0 var = cl_test.myclass()

def __init__(self, x=0):
    self.x = x

您需要將self.x添加到第一個 function 中。 只需將x作為變量放在那里,它就只能在這個 function 中訪問。 使用self.x使其可在整個 class 中訪問。 這是myclass()的最終結果應該是這樣的:

class myclass():
    def fx1(self, a):
        self.x = a
        print(a)

    def fx2(self, b):
        c = self.x + b
        print(c)

在您的代碼中,在 fx2() 中它不知道變量x是什么。 因此,要修復它,您需要編寫self.x ,除了 x 以使用 object 引用 x。

最終結果:

class myclass():
    def fx1(self, a):
        self.x = a
        print(a)

    def fx2(self, b):
        c = self.x + b
        print(c)

和:

import cl_test

var = cl_test.myclass()

var.fx1(5)
var.fx2(3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM