2016-05-19 114 views
0

我正在創建一個程序,用戶可根據用戶輸入和預定義值猜測某人的身份。Python - 將用戶輸入與類對象實例進行比較

class myPeople(object):

`def __init__(self, name, age, gender):` 
`self.name = name` 
`self.age = age` 
`self.gender = gender` 

name=input("What is your name?\n")

age=input("What is your age?\n")

gender=input("What is your gender?\n")

smith = myPeople(name="smith", age="104", gender="female")

john = myPeople(name="john", age="14", gender="male")

我想比較用戶輸入與預先指定爲「smith」和「john」的值。我想,我可以這樣做:

if smith.myPeople is True:

`print("You are Mr. Smith")` 

elif john.myPeople is True:

`print("You are Mr. John")` 

,我發現了錯誤AttributeError的:對象類型 'myPeople' 有沒有屬性 '鐵匠'

另外,我不確定,如果陳述「是真的」將起作用。在此先感謝您的幫助。

+0

你期望'smith.myPeople'完成了什麼? – timgeb

回答

0

您可以通過添加一個comparison method, in this case __eq__customize your class。然後你可以檢查是否類實例是平等的。

class myPeople(object): 
    def __init__(self, name, age, gender): 
     self.name = name 
     self.age = age 
     self.gender = gender 
    def __eq__(self, other): 
     return (self.name == other.name and 
       self.age == other.age and 
       self.gender == other.gender) 

smith = myPeople(name="smith", age="104", gender="female") 
john = myPeople(name="john", age="14", gender="male") 

>>> smith == john 
False 
>>> smith == smith 
True 
>>> john == smith 
False 
>>> john == john 
True 
>>> 

使用用戶的響應來創建另一個實例,然後進行比較。

>>> name = 'smith' 
>>> age = '104' 
>>> gender = 'female' 
>>> foo = myPeople(name = name, age = age, gender = gender) 
>>> foo == smith 
True 
>>> foo == john 
False 
>>> 
相關問題