我正在生成一類人,并希望通過輸入獲取有關某個人的資訊。我想使用str函式,因為我想更好地理解它。我的想法如下:
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" f_name l_name
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
print(person) #I am aware that this just fills in the string saved in person, but how do I connect it to the variable?
另一個想法是按如下方式進行:
#class stays the same except:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
list.append(self)
#and then for the main:
list = []
person1 = Person(Peter, Punk)
person2 = Person(Mia, Munch)
person = input("What persons full name would you like to know?")
index = list(person)
print(list[index])
Thankful for any edvice since I am obviously new to Python :D
uj5u.com熱心網友回復:
我認為 OP 在這里有一些概念問題,這個答案可能會有所幫助。
首先構建一個健壯的類定義。在這種情況下很簡單,因為只有 2 個屬性。請注意使用 setter、getter 和str、repr和eq dunder 覆寫。
一個小函式,用于檢查是否可以在 Person 串列中找到給定的 Person 并相應地報告。
創建一個包含 2 個不同 Person 實體的串列
創建另一個已知不匹配串列中任何內容的 Person。
運行檢查()
修改“獨立”Person 使其等同于先前構造的內容。
運行檢查()
class Person:
def __init__(self, forename, surname):
self._forename = forename
self._surname = surname
@property
def forename(self):
return self._forename
@forename.setter
def forename(self, forename):
self._forename = forename
@property
def surname(self):
return self._surname
@surname.setter
def surname(self, surname):
self._surname = surname
def __str__(self):
return f'{self.forename} {self.surname}'
def __repr__(self):
return f'{self.forename=} {self.surname=}'
def __eq__(self, other):
if isinstance(other, type(self)):
return self.forename == other.forename and self.surname == other.surname
return False
def check(list_, p):
if p in list_:
print(f'Found {p}')
else:
print(f'Could not find {p}')
plist = [Person('Pete', 'Piper'), Person('Joe', 'Jones')]
person = Person('Pete', 'Jones')
check(plist, person)
person.surname = 'Piper'
check(plist, person)
輸出:
Could not find Pete Jones
Found Pete Piper
uj5u.com熱心網友回復:
您可能需要名稱和物件之間的映射。這就是 Python 的dict字典結構的用途:
people = {} # an empty dictionary
people[f'{person1.f_name} {person1.l_name}'] = person1
people[f'{person2.f_name} {person2.l_name}'] = person2
這是創建一個名字和姓氏的字串。
然后,您可以Person使用全名查找物件:
print(people['Peter Punk'])
uj5u.com熱心網友回復:
您可以像這樣使用串列理解來做到這一點(也允許多人擁有相同的名字)
class Person:
__init__(self, f_name, l_name):
self.f_name = f_name
self.l_name = l_name
__str__(self):
return "The persons full name is:" f_name l_name
personList= []
personList.append(Person(Peter, Punk))
personList.append(Person(Mia, Munch))
personName = input("What persons full name would you like to know?")
print([str(person) for person in personList if person.f_name == personName])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485975.html
