-5
我一直在Python 2.7中嘗試踢和練習一個有點愚蠢的OOP腳本。到目前爲止我的代碼如下:Python OOP初學者:參考同一對象的另一個實例的數據
class Human(name, gender, age):
name = self.name
gender = self.gender
age = self.age
def sayHello(target) #where target stands for the other instance I want to interact with
try:
if gender in ["male", "man", "boy"]: #gender: the gender specified on the other instance
print "Howdy, %s!" % target
elif gender in ["female", "woman", "girl"]:
print "Hiya there %s, what's up??" % target
except NameError:
print "Nobody to greet here... :("
def introduceYourself():
print """Hello everyone! My name is %s and I am a %s-year old %s,
who lives happily in a small house by the river.""" % (name, age, gender)
def kick(target):
if target == None:
print "Woo-haw! *breaks a piece of wood into shards"
else:
try:
target.getKicked()
except NameError:
print "whoosh"
def getKicked():
print "OUCH! That hurt, %s! Seriously." % name (from the other instance)
alice = Human("Alice Withings", "woman", 23)
bob = Human("Robert Jones", "man", 25)
我想要做的是這樣的:爲了鮑勃或翹互相問候各自的名稱,例如。當告訴鮑勃向愛麗絲問好時(如Bob.sayHello(愛麗絲)],他應該回應:「你好,愛麗絲!」。愛麗絲也是如此。
對於踢腿(雙關不打算),同樣的原則適用。
在此先感謝。
PS。我在深夜寫這篇文章,所以如果你發現任何語法或其他錯誤,請毫不猶豫地糾正我。我仍然在學習;)
您的代碼中存在*明確* indentation錯誤,而這不是類定義的樣子。無論如何,問題是什麼? –
我修復了你的初始化邏輯和縮進。請添加一個或兩個電話,更新名稱字段,嘗試運行您的代碼,然後更新此帖子(或發佈新帖子),如果您仍有問題 – Prune
@Prune不要編輯asker的代碼,並在其中修復錯誤他們的錯誤!有了12k的聲望,你應該知道Stack Overflow是如何工作的。我回滾了你的編輯,請留下來。 –