簡體   English   中英

如何打印存儲在 class 內的變量中的值

[英]how to print the value stored in a variable inside a class

我想打印存儲在 self.datafame 中的數據,但它在 class 和 function 以及 class 之外不起作用,它給了我一個錯誤 self is not defined。 任何知道如何打印它的人。

class CustomDataSet(Dataset):
def __init__(self, csv_file, root_dir, transform):
    self.root_dir = root_dir
    self.transform = transform
    self.dataframe = pd.read_csv(csv_file, low_memory=False)

def __len__(self):
    return len(self.dataframe)

def __getitem__(self, idx):
    if torch.is_tensor(idx):
        idx = idx.tolist()
    img_path = self.dataframe.iloc[idx, 15]
    image = Image.open(img_path).convert("RGB")

    tensor_image = self.transform(image)
    return tensor_image

錯誤是:

    Traceback (most recent call last)
Input In [33], in <cell line: 19>()
     16         tensor_image = self.transform(image)
     17         return tensor_image
---> 19 print(self.dataframe)

NameError: name 'self' is not defined

在你的例子中你有

    Traceback (most recent call last)
Input In [33], in <cell line: 19>()
     16         tensor_image = self.transform(image)
     17         return tensor_image
---> 19 print(self.dataframe)

作為您的錯誤,據我所知,您正在 class 定義之后立即打印。

這在 function 之外。 當訪問一個對象的變量時,你想調用對象的變量名,然后是你試圖訪問的屬性。 例如,如果您這樣做:

custom_dataset = CustomDataSet("../path/to/file", "my_root_dir", "my_transform")

# you can then do:
print(custom_dataset.dataframe) 

暫無
暫無

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

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