[英]Does Python support forward declaration in class?
# animal.py
class Animal:
def __init__(self):
self.action = {'feed':feed_pet}
def do_action(self, a):
action[a]()
def feed_pet(self):
print('Gives some food')
# main.py
from animal import *
my_pet = Animal()
my_pet.do_action('feed')
我想制作游戲,但是這段代碼給了我以下錯誤:
Traceback (most recent call last):
File "so.py", line 3, in <module>
my_pet = Animal()
File "/home/wdwickar/pyside/animal.py", line 4, in __init__
self.action = {'feed':feed_pet}
NameError: name 'feed_pet' is not defined
Python中沒有像C這樣的前向聲明嗎?
問題是您不了解python類,您所指的是全局范圍的名稱feed_pet
但您打算在該類中調用該函數,因為您需要使用self
,請檢查以下更改:
class Animal:
def __init__(self):
self.action = {'feed':self.feed_pet}
def do_action(self, a):
self.action[a]() //use self also for access instance attributes
def feed_pet(self):
print('Gives some food')
# main.py
from animal import *
my_pet = Animal()
my_pet.do_action('feed')
為了清楚起見,Python是否支持類中的前向聲明?
不需要在python中進行前向聲明,與C不同,您可以根據需要多次重新定義任何對象,python會將最后一個對象保留為活動對象。 另外,由於它在編譯時沒有靜態類型,因此可以將任何變量用作任何類型,因此無需聲明任何內容即可使用它,只是在運行時必須處於同一作用域內。
請使用self.action = {'feed': self.feed_pet}
來引用綁定實例函數。
沒有全局名稱feed_pet
。
您在兩個參考中的每個參考中都沒有激活必需的對象。 沒有通用功能feed_pet
或變量action
。 有實例方法-所以你必須在每個引用(電話),以提供實例。 下面的代碼解決了單行輸出“給些食物”的問題。 請注意我添加self.
的兩個地方self.
通話。
# animal.py
class Animal:
def __init__(self):
self.action = {'feed': self.feed_pet} # Add "self"
def do_action(self, a):
self.action[a]() # Add "self"
def feed_pet(self):
print('Gives some food')
另外,請注意,這里沒有聲明 ,除了函數定義中隱含的聲明 。 Python只需要您在調用函數之前就定義好該函數。
首先要弄清楚一些基本概念:
1. self參數是指向類實例的引用。
2.通過使用self,我們可以訪問類的屬性和方法。
在您的代碼中,您引用了全局范圍變量和方法。 使用自指針引用類變量和方法。
例如self.action = {'feed':self.feed_pet}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.