這裏對象添加到Python的集收集,並確定是我的代碼:通過對象的屬性
#!/usr/bin/python
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def get_detail(self):
print "I am %s , my age is %d" % (self.name, self.age)
if __name__ == '__main__':
tom = Person('tom', 18)
jack = Person('jack', 20)
mary = Person('mary', 22)
mary2 = Person('mary2', 22)
mary3 = Person('mary3', 22)
person_set = set([])
person_set.add(tom)
person_set.add(jack)
person_set.add(mary)
person_set.add(mary2)
person_set.add(mary3)
for man in person_set:
man.get_detail()
結果:
I am jack , my age is 20
I am mary2 , my age is 22
I am tom , my age is 18
I am mary , my age is 22
I am mary3 , my age is 22
預期結果:
I am jack , my age is 20
I am tom , my age is 18
I am mary , my age is 22
按照預期結果,我的意思是當我將Person
添加到person_set
中時,我想確定新人是否已經完全通過屬性age
。什麼是正確的方式來做到這一點?
所以,作爲一個例子,'弗蘭克,年齡19'將是一樣'希瑟,19'年代,如果你只是按年齡比較? – jamylak
是的,只有第一個被添加到集合中才會被存儲 – sashimi
@sashimi,那麼你需要一個字典,其中age作爲key,Person對象作爲值。 – spinlok