I'm trying to create a loop to print data from all people in list. I have created:
Class –> event
List –> list
Function –> dane
class event:
def __init__(self, imie, nazwisko, firma, stanowisko, mail):
self.imie = imie
self.nazwisko = nazwisko
self.firma = firma
self.stanowisko = stanowisko
self.mail = mail
JagodaSobczak = event(imie="Jagoda", nazwisko="Sobczak")
DitaKowalska = event(imie="Dita", nazwisko="Kowalska")
JaromirOstrowski = event(imie="Jaromir", nazwisko="Ostrowski")
MakaryKalinowski = event(imie="Makary", nazwisko="Kalinowski")
DrugiSzczepański= event(imie="Drugi", nazwisko="Szczepanski")
list = ["JagodaSobczak", "DitaKowalska", "JaromirOstrowski", "MakaryKalinowski",
"DrugiSzczepański"]
The function works, but I need to enter its argument. For example: data(JagodaSobczak).
def dane(name):
print(name.imie, name.nazwisko)
dane(JagodaSobczak)
I want to create loop for to get data from a list and print class information for it. Repeat the whole process as many times as there are arguments in the list - in this case 5 times. Repeat can by done by len(list), but I'm stuck on creating a loop.
I created loop and I tried:
for i in list:
x = next(list_iterator)
dane(x) / dane(i)
CodePudding user response:
If you intentionally made list contain string representations of the object names as opposed to the objects themselves, then you need to use use globals() to access the actual objects:
list = ["JagodaSobczak", "DitaKowalska", "JaromirOstrowski", "MakaryKalinowski",
"DrugiSzczepański"]
for i in list:
dane(globals()[i])
Otherwise, if you have no reason to keep track of these names as strings, you can make it more simple:
list = [JagodaSobczak, DitaKowalska, JaromirOstrowski, MakaryKalinowski,
DrugiSzczepański]
Then your loop will look something like:
for i in list:
dane(i)
CodePudding user response:
from dataclasses import dataclass
@dataclass
class Person:
imie: str
nazwisko: str
firma: Optional[str]
stanowisko: Optional[str]
mail: Optional[str]
def dane(self):
print(self.imie, self.nazwisko)
if __name__ == '__main__':
# Instantiate the people
people = (
Person(imie="Jagoda", nazwisko="Sobczak"),
Person(imie="Dita", nazwisko="Kowalska"),
Person(imie="Jaromir", nazwisko="Ostrowski"),
Person(imie="Makary", nazwisko="Kalinowski"),
Person(imie="Drugi", nazwisko="Szczepanski")
)
for person in people:
person.dane()