我正在创建一个程序,人们会根据用户输入和预定义值来猜测某人的身份。
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:type object'myPeople'没有属性'smith'
此外,我不确定,如果声明“是真的”将起作用。在此先感谢您的帮助。
答案 0 :(得分:0)
您可以customize your class添加comparison method, in this case __eq__
。然后你可以检查一下类实例是否相等。
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
>>>