我正在嘗試做應該是簡單的字串比較,但我無法讓它作業:
class Bonk:
def __init__(self, thing):
self.thing = thing
def test(self):
if self.thing == 'flarn':
return 'you have flarn'
return 'you have nothing'
bonk1 = Bonk('glurm')
bonk2 = Bonk('flarn')
bonk1.test()
bonk2.test()
這不回傳任何內容。我也試過這個:
def test(self):
if self.thing in ['flarn']:
...
這也不起作用。
我試過雙引號,將 'flarn' 分配給一個變數,然后針對該變數進行測驗,在串列測驗的末尾添加一個逗號。我嘗試將它作為變數傳入......但沒有任何效果。
我錯過了什么?
uj5u.com熱心網友回復:
您對如何撰寫 OOP 類有點錯誤,盡管這是一個很好的嘗試,因為您走在正確的軌道上!
這是您要實作的目標的有效實作:
class Bonk:
def __init__(self, thing):
self.thing = thing
def test(self):
if (self.thing == 'flarn'):
return 'you have flarn'
return 'you have nothing'
bonk1 = Bonk('glurm')
bonk2 = Bonk('flarn')
print(bonk1.test()) # you have nothing
print(bonk2.test()) # you have flarn
解釋
創建 Python 物件時,__init__會呼叫自定義函式以將屬性分配給物件。
def __init__(self, thing): # Bonk object constructor with property
self.thing = thing # Set the property for this object
然后,您可以為每個物件創建其他函式,例如test(),它將self作為第一個引數,在呼叫時參考物件本身。
def test(self):
if (self.thing == 'flarn'): # Check the saved property of this object
return 'you have flarn'
return 'you have nothing'
相關檔案: https : //docs.python.org/3/tutorial/classes.html#class-objects
uj5u.com熱心網友回復:
去掉注釋和其他建議的解決方案,您也可以這樣做,并通過在初始化程式中實作該函式檢查來避免使用另一個函式def test()。較少的代碼行就可以完成作業。
class Bonk:
def __init__(self, thing):
self.thing = thing
if self.thing == 'flarn':
print('you have flarn')
else:
print('you have nothing')
bonk1 = Bonk('glurm')
bank2 = Bonk('flarn')
=== output ===
you have nothing
you have flarn
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367104.html
