[英]In class creation, the function call is not answered
我正在學習OOP函數,因此在調用Plant類時遇到問題。 這是我的代碼,我得到未定義名稱Plant的錯誤代碼。
class Plant:
def __init__(self, name, biomass):
self.name = name
self.mass = biomass
def getName(self):
return str(self.name)
def getMass(self):
return float(self.mass)
def setMass(self,mass):
self.mass=mass
tree = Plant('red oak', 1042)
flower = Plant('rose', 2.7)
#tree.getName() --> 'red oak'
flower.setMass(2.85)
#flower.getMass() --> 2.85
謝謝您的幫助!
如果當前問題的代碼縮進與您的編輯器中的縮進匹配,則您正在嘗試在類定義本身內部聲明Plant
的實例。
您的代碼最終應該看起來像這樣:
class Plant:
def __init__(self, name, biomass):
self.name = name
self.mass = biomass
def getName(self):
return str(self.name)
def getMass(self):
return float(self.mass)
def setMass(self,mass):
self.mass=mass
tree = Plant('red oak', 1042)
flower = Plant('rose', 2.7)
#tree.getName() --> 'red oak'
flower.setMass(2.85)
#flower.getMass() --> 2.85
否則,這很像告訴您要使它成為Plant
的語言,但您還沒有說完該語言是什么Plant
!
Python特別強調縮進,如果一行的縮進與上面的行的縮進相同,則它們都被解釋為位於同一代碼塊中。
https://docs.python.org/release/2.5.1/ref/indentation.html
當前,您的代碼正在嘗試在類內部創建一個類對象。 (您不能在該類中創建該類的對象)修復縮進:
class Plant:
def __init__(self, name, biomass):
self.name = name
self.mass = biomass
def getName(self):
return str(self.name)
def getMass(self):
return float(self.mass)
def setMass(self,mass):
self.mass=mass
tree = Plant('red oak', 1042)
flower = Plant('rose', 2.7)
#tree.getName() --> 'red oak'
flower.setMass(2.85)
#flower.getMass() --> 2.85
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.