簡體   English   中英

Visual Studio 社區 2019 + Python

[英]Visual Studio Community 2019 + Python

我在 Visual Studio 社區版中做了以下簡單的類:

class Check(object):
def __init__(self):
    self.t = 5

但是當運行時

from Check import Check
try:
    print(Check.t)
except Exception as Err:
    print(str(Err))

或者

    import Check
    try:
       print(Check.t)
    except Exception as Err:
       print(str(Err))

我得到以下錯誤:

The object 'Check' has no attribute 't'

這也很奇怪,因為關鍵字“self”沒有顯示為 Python 關鍵字或 Buildin func。

您必須先實例化檢查對象,然后才能訪問它。

這可以通過以下方式完成

from Check import Check
try:
    print(Check().t)
except Exception as Err:
    print(str(Err))

當您嘗試調用 Check.t 時,它試圖訪問不存在的類元素“t”。

關於視覺工作室社區的信息在這里是多余的。

問題在於你如何定義和調用你的類。 您已經創建了一個類(藍圖),但在調用屬性(變量 t)時還沒有創建任何實例(實際對象)。

假設您有一個名為check.py的模塊,您在其中定義了簡單類。

# check.py

class Check:
    def __init__(self):
        self.t = 5

現在從模塊check.py導入類Check

from check import Check

# create an instance of the class
ins = Check()

# access and print the attribute
try:
    att = ins.t
    print(att)
except Exception as err:
    print(str(err))

暫無
暫無

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

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