[英]NameError: name 'Class_Name' is not defined
我有一個問題,就是我不斷收到 NameError 的錯誤:未定義名稱“Class_Name”。 我明白了。 棘手的部分是我的代碼看起來像這樣:
class FirstClass():
second_class: SecondClass
def __init__(self):
"""SOME CODE HERE"""
class SecondClass(firsClass: FirstClass):
def __init__(self):
self.first_class = firstClass
所以問題是,無論我如何安排代碼,我總會有一個在另一個上面,所以它總是說沒有定義。 我該如何解決這個問題?
----------------------解決方案------------------------ ---
我找到了解決方案。 如果你使用導入
from __future__ import annotations
它將讀取文件,您將能夠調用這些類,即使它們是在代碼的后面定義的。
from pprint import pp
class FirstClass():
#for typing, if you want to indicate a class variable
second_class: type["SecondClass"]
#for typing, if you want to indicate an instance variable
second_class_instance: "SecondClass"
def __init__(self):
"""SOME CODE HERE"""
self.second_class_instance = self.second_class()
#this looks off in the inheritance declaration - dont specify types here
#class SecondClass(firsClass: FirstClass):
class SecondClass(FirstClass):
def __init__(self):
#this code will error, watch your cases!
#self.first_class = firstClass
...
#for doing something with the second_class attribute, later in the runtime
#however, no tricks with "SecondClass" quoting allowed, you need
#to wait till both FirstClass and SecondClass EXIST, which is why
#this line is here, with this indentation
FirstClass.second_class = SecondClass
first = FirstClass()
pp(first)
pp(vars(first))
這樣做是個好主意嗎? 可能不是,但可能有特殊的理由來跟蹤second_class
class 引用,比如調用 class 構造函數而不在 FirstClass 方法中對 SecondClass 進行硬編碼。
而且,在這個方案中,我更不相信擁有 SecondClass 子類 FirstClass,但是......
% py test_429_declare.py
<__main__.FirstClass object at 0x10841f220>
{'second_class_instance': <__main__.SecondClass object at 0x10841f250>}
和mypy
% mypy test_429_declare.py
Success: no issues found in 1 source file
實際上,我找到了解決方案。
如果我們使用 import from __future__ import annotations
它將讀取文件並且不會有那個問題,所以我們可以按照我們想要的順序引用不同的東西。 舉個例子:
class FirstClass():
second_class: SecondClass
def __init__(self):
"""SOME CODE HERE"""
class SecondClass(firsClass: FirstClass):
def __init__(self):
self.first_class = firstClass
這將被解決為:
from __future__ import annotations
class FirstClass():
second_class: SecondClass
def __init__(self):
"""SOME CODE HERE"""
class SecondClass(firsClass: FirstClass):
def __init__(self):
self.first_class = firstClass
您可以在 python 文檔中找到更多詳細信息: https://docs.python.org/3/library/__future__.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.