Printing classes in Python with multiple values - python

I have spent a good while searching through this website so I hope this question hasn't been asked before - apologises if it has. I'm learning classes for the first time and I'm making a class with multiple users (could be 50+ but for now, I just have 2 in my example). What I'm trying to do is have certain information about users/employees and be able to print them all in one go... in a way that isn't a complete eyesore! This is what I have attempted:
class User:
def __init__(self, user_id, first, last, address):
self.user_id = user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '#python.com'
def all_users(self):
print()
print('User ID: {} First Name: {} {} {} {}'.format(self.user_id, self.first, self.last, self.address, self.email))
print()
user_1 = User(123, 'Kim', 'N', 'London')
user_2 = User(312, 'Chris', 'E', 'Japan')
print(all_users(User))
This is the error message that I am receiving:
print('User ID: {} First Name: {} {} {} {}'.format(self.user_id, self.first, self.last, self.address, self.email))
AttributeError: type object 'User' has no attribute 'user_id'
Thanks in advance for any help or guidance.

Sounds like you want the User class to contain a list of all users.
This is called a class variable because it is attached to the class itself, instead of being attached to a particular instance of the class.
Example code:
class User(object):
users = []
def __init__(self, first, last):
self.first = first
self.last = last
# now that this instance is fully initialized, add it
# to the master list of users
User.users.append(self)
def __str__(self):
return '{} {}'.format(self.first, self.last)
#staticmethod
def all_users():
for user in User.users:
print (user)
user_1 = User('Kim', 'Smith')
user_2 = User('Chris', 'Jones')
User.all_users()

You should probably implement the __str__ or __repr__ special methods, which are designed to print human readable and "official" representations of the class instances, respectively
class User():
...
def __str__(self):
attrs = ['{}={}'.format(k, repr(v)) for k, v in self.__dict__.items()]
return '{}({})'.format(self.__class__.__name__, ', '.join(attrs))
Then it would look like this
>>> user = User('123', 'John', 'Doe', 'USA')
>>> print(user)
User(user_id='123', first='John', last='Doe', address='USA', email='John.Doe#python.com')

Related

Create a method that lists instances that were set to True in a previous class

I have the following code that records job candidates' personal details in a class Employee:
class Employee:
def __init__(self, name, role, id):
self.name = name
self.role = role
self.id = id
self.interviewed = False
def __str__(self):
text = f'Candidate {self.name}; {self.id}. '
if self.interviewed == False:
return text + 'Not interviewed yet.'
else:
return text + 'Interviewed.'
def interview(self):
self.interviewed = True
I also have another class Database that lists all the candidates in a database for a particular employer:
class Database:
def __init__(self, company, employer):
self.company = company
self.employer = employer
self.candidates = []
def __str__(self):
text = f'{The hiring company is {self.company} and the employers name is {self.employer}'
return text
def add_candidate(self, candidate):
self.candidates.append(candidate)
Now, if we record personal details of two candidates in the class Employee and add them to the class Database using the method add_candidate, how do I create a new method called list_interviewed_candidates(self) in the class Database that will print all candidates that have self.interviewed set to True?
This is what I tried:
class Database:
def __init__(self, company, employer):
self.company = company
self.employer = employer
self.candidates = []
def __str__(self):
text = f'{The hiring company is {self.company} and the employers name is {self.employer}'
return text
def add_candidate(self, candidate):
self.candidates.append(candidate)
def list_interviewed_candidates(self):
for employee in self.candidates:
if employee.interviewed == True:
return employee
But that doesn't work. I have also tried list comprehension but it seems I just cannot access the boolean value that was set in the first class. Ideally, the output should look something like this:
database1 = Database('Google', 'Jack H')
print(database1)
'The hiring company is Google and the employers name is Jack H'
candidate1 = Employee('Anna S', 'web-designer', 12)
database1.add_candidate(candidate1)
print(database1.list_interviewed_candidates())
[]
candidate1.interview()
print(database1.list_interviewed_candidates())
['Candidate Ana S; 12 - Interviewed']
In your Database.list_interviewed_candidates method you are returning the first employee that was interviewed. Keep in mind that return exits from the current function (method in this case) as soon as is hit.
So it starts looking at your candidates and as soon as one interviewed is found, it returns that one.
You probably want to gather them all in a list and return that:
def list_interviewed_candidates(self):
retval = []
for employee in self.candidates:
if employee.interviewed == True:
retval.append(employee)
return retval
Something pretty interesting you could also use is yield:
def list_interviewed_candidates(self):
for employee in self.candidates:
if employee.interviewed == True:
yield employee
Which... you can try by doing:
print(list(database1.list_interviewed_candidates()))
Pretty cool. This opens the really fun world of iterators!
A list comprehension works, but realize __str__ is used by print but __repr__ is used for items displayed in a list. __repr__ is also used if __str__ isn't defined.
Try the following, but change __str__ to __repr__ in Employee:
def list_interviewed_candidates(self):
return [employee for employee in self.candidates if employee.interviewed]
Then:
database1 = Database('Google', 'Jack H')
print(database1)
candidate1 = Employee('Anna S', 'web-designer', 12)
candidate2 = Employee('Mark T', 'pythonista', 13)
database1.add_candidate(candidate1)
database1.add_candidate(candidate2)
print(database1.list_interviewed_candidates())
candidate1.interview()
candidate2.interview()
print(database1.list_interviewed_candidates())
Outputs:
The hiring company is Google and the employers name is Jack H
[]
[Candidate Anna S; 12. Interviewed., Candidate Mark T; 13. Interviewed.]
Customize __str__ and __repr__ individually if you want differing output between direct print of Employee and how it is displayed in a list.

How to call object of class by input?

I am generating a class of persons and want to get information about a certain person by input. I would like to use the str funtction because I am trying to understand it better. My Idea goes as follows:
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?
another idea was to do it as follows:
#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
I think OP has some concept problems here which this answer may go some way to help with.
Start by building a robust class definition. Simple in this case as there are just 2 attributes. Note the use of setters, getters and str, repr and eq dunder overrides.
A small function that checks if a given Person can be found in a list of Persons and reports accordingly.
Create a list with 2 different Person instances
Create another Person that is known not to match anything already in the list.
Run check()
Modify the 'standalone' Person to make it equivalent to something previously constructed.
Run check()
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)
Output:
Could not find Pete Jones
Found Pete Piper
You probably want a mapping between a name and an object. This is what Python's dict dictionary structure is for:
people = {} # an empty dictionary
people[f'{person1.f_name} {person1.l_name}'] = person1
people[f'{person2.f_name} {person2.l_name}'] = person2
This is creating a string of the first and last name.
You can then lookup the Person object using the full name:
print(people['Peter Punk'])
You could do this with list comprehension like so (also allowing multiple people to have the same first name)
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])

Adding multiple variables in an object - need further assistance

First thing first - upon suggestions, please do your best to be understandable for newbies as if it is too complex, it may not be much useful as I need to furtherly continue after the current ask. Thank you in advance for that :)
I'm trying to define an object with multiple variables that I may use.
So far I was able to create the basic class for myself (with just ID of the object), but I am now struggling to add the rest of the variables needed for the object.
The data that I have to store with the multiple instance of the object is as follows:
id of the user - this is the value thru which I need to be searching thru the objects as I will have multiple entries of the below example data for different time intervals that I need to count. It does not need to be changed within the objects variables.
Name - The name of the person for whom I will be counting the hours spent. It is static (does not need to be changed within the objects variables).
Started timestamp and Ended timestamp - The time within which the person has executed things. As I will have multiple instances of data coming towards the object, I need to check for overlapping of shifts and if so, such hours to be avoided, but if extra hours beside the overlapped - to be added. E.g. if overlapping is not a perfect match, then the additional time spent to be added to the "total spent hours". The data received for both timestamps are in format that I convert into datatime with "datetime.strptime(start, '%Y-%m-%dT%H:%M:%S+02:00')
Schedule ID - it is the ID of the entry for the started and ended timestamps. It may be saved as an array as it will not be used except for reporting purposes - e.g. the person has processed things during it's first shift (start_timestamp thru end_timestamp).
Array of contacts that I need to separate to two different values - one for e-mail, other for phone number (including country code). The array returns as [email, country_code, phone_number]
Quote of example data that I have:
PersonID: ID1234
Name: Anton Todorov
Started at: 2022-12-26T00:00:00+02:00
Ended at: 2022-12-26T02:00:00+02:00
Schedule ID: SCHEDID1
Contacts: ['a.todorov#e-mail.email', 359, '000000000']
---===Separator===---
PersonID: ID5678
Name: Morgan Freeman
Started at: 2022-12-26T02:00:00+02:00
Ended at: 2022-12-26T14:00:00+02:00
Schedule ID: SCHEDID2
Contacts: ['slogan#draftkings.com', 1, '0000000000']
---===Separator===---
PersonID: ID1234
Name: Anton Todorov
Started at: 2022-12-26T14:00:00+02:00
Ended at: 2022-12-27T02:00:00+02:00
Schedule ID: SCHEDID3
Contacts: ['a.todorov#e-mail.email', 359, '000000000']
So with that on, I have to calculate the total hours that each person has spend from within these sections of data that I have.
The object that I have so far is as follows:
class DataItem(object):
def __init__(self, person_id):
self._person_id = person_id
self._updatable_id = ""
#property
def person_id(self):
return self._person_id
#property
def updatable_id(self):
return self._updatable_id
#updatable_id.setter
def updatable_id(self, value):
self._updatable_id = value
#updatable_id.deleter
def updatable_id(self):
del self._updatable_id
class Persons(object):
def __init__(self):
self._ids = []
def find_person_by_id(self, person_id):
# search by id
existing = [i for i in self._ids if i.person_id == person_id]
if not existing:
# create and append
existing_person = DataItem(id)
self._ids.append(existing_person)
else:
# assign to existing
existing_person = existing[0]
# return the object to be acted upon
return existing_person
So.. Would someone be able to assist me with furtherly developing the object so that I may be storing the data properly inside of each of its instances, please?
I would gladly appreciate all detailed suggestions (especially as soon as I am also able to understand them).
Thank you all in advance!
I finally developed what I was looking for.
A bit messy, but that does exactly what I need.
Thanks to #Robert Lee for the attempt, despite it was not what I chose to continue with.
class PersonData(object):
def __init__(self, email, country_code, phone_number, user_id, names):
self._email = email
self._country_code = country_code
self._phone_number = phone_number
self._user_id = user_id
self._names = names
self._started = []
self._ended = []
self._schedule_id = []
#property
def email(self):
return self._email
#property
def country_code(self):
return self._country_code
#property
def phone_number(self):
return self._phone_number
#property
def user_id(self):
return self._user_id
#property
def names(self):
return self._names
#property
def started(self):
return self._started
#started.setter
def started(self, started):
self._started.append(started)
#started.deleter
def started(self):
del self._started
#property
def ended(self):
return self._ended
#ended.setter
def ended(self, ended):
self._ended.append(ended)
#ended.deleter
def ended(self):
del self._ended
#property
def schedule_id(self):
return self._schedule_id
#schedule_id.setter
def schedule_id(self, schedule_id):
self._schedule_id.append(schedule_id)
#schedule_id.deleter
def schedule_id(self):
del self._schedule_id
class PeopleBuffer(object):
def __init__(self):
self._people = []
def find_by_id(self, email, country_code, phone_number, user_id, names):
# search by id
existing = [i for i in self._people if i.user_id == user_id]
if not existing:
# create and append if not found
existing_person = PersonData(email, country_code, phone_number, user_id, names)
self._people.append(existing_person)
else:
# assign to existing
existing_person = existing[0]
# return an object to be acted upon
return existing_person
def return_all(self):
for each_person in self._people:
print("each_person: ")
print("Email: %s" % each_person.email)
print("Country Code: %s" % each_person.country_code)
print("Phone Number: %s" % each_person.phone_number)
print("User Id: %s" % each_person.user_id)
print("Names: %s" % each_person.names)
print("Started: %s" % each_person.started)
print("Ended: %s" % each_person.ended)
print("ScheduleId: %s" % each_person.schedule_id)
class MainApplication(object):
def __init__(self):
self._buffer = PeopleBuffer()
def _populate_person(self, email, country_code, phone_number, user_id, names, started, ended, schedule_id):
person = self._buffer.find_by_id(email, country_code, phone_number, user_id, names)
person.started.append(started)
person.ended.append(ended)
person.schedule_id.append(schedule_id)
def _print_people(self):
self._buffer.return_all()
def main(self):
while input("Continue? ") != "No":
user_id = input("Enter UserId: ")
names = input("Enter Name: ")
started = input("Enter Started: ")
ended = input("Enter Ended: ")
schedule_id = input("Enter ScheduleId: ")
email = input("Enter Email: ")
country_code = input("Enter CountryCode: ")
phone_number = input("Enter PhoneNumber: ")
self._populate_person(email, country_code, phone_number, user_id, names, started, ended, schedule_id)
self._print_people()
def main():
app = MainApplication()
app.main()
if __name__ == '__main__':
main()
Based on what you are doing I would consider doing json data format and do something like this. Please excuse my quick and dirty code but I think fundamentally you are looking for a way to create a data format that might work for your scenario.
Looking over it one more time, I feel like this might be the format you are looking for
[
{
"person_id": "ID1234",
"name": "Anton Todorov",
"schedule": [
{
"schedule_id": "SCHEDID1",
"started_at": "2022-12-26T00:00:00+02:00",
"ended_at": "2022-12-26T02:00:00+02:00"
},
{
"schedule_id": "SCHEDID3",
"started_at": "2022-12-26T14:00:00+02:00",
"ended_at": "2022-12-27T02:00:00+02:00"
}
],
"contact_info": {
"email": "a.todorov#e-mail.email",
"country_code": 359,
"phone_number": "000000000"
}
},
{
"person_id": "ID5678",
"name": "Morgan Freeman",
"schedule": [
{
"schedule_id": "SCHEDID2",
"started_at": "2022-12-26T02:00:00+02:00",
"ended_at": "2022-12-26T14:00:00+02:00"
}
],
"contact_info": {
"email": "slogan#draftkings.com",
"country_code": 1,
"phone_number": "000000000"
}
}
]
Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
def main():
people = list()
person = dict()
person['person_id'] = 'ID1234'
person['name'] = 'Anton Todorov'
person['schedule'] = list()
schedule = dict()
schedule['schedule_id'] = 'SCHEDID1'
schedule['started_at'] = '2022-12-26T00:00:00+02:00'
schedule['ended_at'] = '2022-12-26T02:00:00+02:00'
person['schedule'].append(schedule)
schedule = dict()
schedule['schedule_id'] = 'SCHEDID3'
schedule['started_at'] = '2022-12-26T14:00:00+02:00'
schedule['ended_at'] = '2022-12-27T02:00:00+02:00'
person['schedule'].append(schedule)
contact_info = dict()
contact_info['email'] = 'a.todorov#e-mail.email'
contact_info['country_code'] = 359
contact_info['phone_number'] = '000000000'
person['contact_info'] = contact_info
people.append(person)
person = dict()
person['person_id'] = 'ID5678'
person['name'] = 'Morgan Freeman'
person['schedule'] = list()
schedule = dict()
schedule['schedule_id'] = 'SCHEDID2'
schedule['started_at'] = '2022-12-26T02:00:00+02:00'
schedule['ended_at'] = '2022-12-26T14:00:00+02:00'
person['schedule'].append(schedule)
contact_info = dict()
contact_info['email'] = 'slogan#draftkings.com'
contact_info['country_code'] = 1
contact_info['phone_number'] = '000000000'
person['contact_info'] = contact_info
people.append(person)
print(json.dumps(people, indent=4))
if __name__ == '__main__':
main()
First things first; Your example feels more like a Java example written in Python. Instance variables are in practice properties, so all of your #property methods is redundant code.
dataclasses module is implemented for cases like yours. For example,
Schedule data class:
# schedule.py
from dataclasses import dataclass, field
from datetime import datetime
from typing import Union
#dataclass(unsafe_hash=True)
class Schedule:
schedule_id: str
start: Union[str, datetime]
end: Union[str, datetime]
def __post_init__(self):
self.start = self._datetime_converter(self.start)
self.end = self._datetime_converter(self.end)
def _datetime_converter(self, dt: str):
return datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S+02:00')
def overlaps_with(self, other: Schedule):
return not ((self.start >= other.end) ^ (other.start >= self.end))
#property
def deltatime(self):
return self.end - self.start
Worker data class:
# worker.py
from functools import reduce
from dataclasses import dataclass, field
from .schedule import Schedule
#dataclass
class Worker:
person_id: str
name: str
contacts: str = field(repr=False)
schedules: set[Schedule] = field(init=False, default_factory=set)
email: str = field(init=False, default='')
country: int = field(init=False, default=-1)
phone: str = field(init=False, default='')
def __post_init__(self):
self.email, self.country, self.phone = self.contacts
#classmethod
def add_from_json(cls, worker_id: str, file: str):
NotImplemented
def overlapping_schedules(self, schedule: Schedule):
return filter(lambda s: s.overlaps_with(schedule), self.schedules)
def schedule_overlaps(self, schedule: Schedule):
return any(self.overlapping_schedules(schedule))
def add_schedule(self, schedule: Schedule):
if not self.schedule_overlaps(schedule):
self.schedules.update({schedule})
else:
NotImplemented
def add_schedules_from_json(self, file: str):
NotImplemented
def remove_schedule(self, schedule: Schedule):
self.schedules -= {schedule}
#property
def total_time_scheduled(self):
deltas = map(lambda s: s.deltatime, self.schedules)
return reduce(lambda x, y: x + y, deltas)
def __hash__(self):
return hash(id(self.person_id))
def __eq__(self, other):
return self.person_id == other.person_id
In theory you don't really need to create a Workers class. The methods __hash__ and __eq__ take care of that and you just need to create a set[Worker]. However, if you still want to create a Workers class, just loop over the existing methods.

Pytest - how to stub member variable

I apologise - this is my first attempt at using pytest or any python testing library, but I have done a small amount of JUnit so am vaguely familiar with the principles.
Basically, the class I want to test has a couple of member variables that I want to stub. Specifically, I only need some customer details. I access this under the OrderController class in its class variable 'orders' (a list of dictionaries with purchase id as key and order objects as values). When I get this order object I would like to access the customer attribute which is comprised of their name and address - this address attribute is another member variable.
Below is the address_label.py module (I'm sorry about the comments - it is for University)
"""
--------------------------------------------------------------------------------------------
title : address_label.py
description : Formats order data for creation of address labels in the pdf.py module.
python_version : 3.7.9
--------------------------------------------------------------------------------------------
"""
from .order_controller import OrderController
from .pdf import Pdf
class AddressLabel:
"""
A class for formatting data to be input into address label pdf.
...
Attributes
----------
order_controller : OrderController
member variable to access order instances
pdf : Pdf
member variable to invoke writing of pdf
Methods
-------
create_address_label(orders_selected):
Create strings to be output in pdf
"""
def __init__(self):
"""
Constructs all the necessary attributes for the AddressLabel object.
"""
self._order_controller = OrderController(None)
self._pdf = Pdf()
def create_address_label(self, orders_selected):
"""
For each of the orders selected with checkboxes will find the data for that order
and format is suitable for the pdf module.
Parameters:
orders_selected: an array of the row data from each row checked with a checkbox
(each item is a string).
"""
for index, order in enumerate(orders_selected):
order_id = int(order[0]) - 1
order_obj = self._order_controller.orders['order_' + order[0]]
address = [order_obj.customer.first_name + ' ' + order_obj.customer.last_name,
order_obj.customer.address.line_one, order_obj.customer.address.city]
self._pdf.write_address_label(address, order_id, index)
return address, order_id, index
This is what I have so far for test_address_label.py, but I notice that it is still contacting the main OrderController class and therefore failing - how can I stop this?
import pytest
from main.business_logic.address_label import AddressLabel
class Address:
def __init__(self, line_one, line_two, city):
self.line_one = line_one
self.line_two = line_two
self.city = city
class Customer:
def __init__(self, address, first_name, last_name):
self.address = address
self.first_name = first_name
self.last_name = last_name
class Order:
def __init__(self, customer):
self.customer = customer
class OrderController:
orders = {
'order_1': Order(customer=setup_customer())
}
def __init__(self, x):
pass
#staticmethod
def setup_customer():
def setup_address():
return Address(line_one='Test Line One',
line_two='Test Line Two', city='Test City')
address = setup_address()
return Customer(address=address, first_name='Test First Name', last_name='Test Last Name')
#pytest.fixture
def _order_controller():
return OrderController()
def test_address_label(_order_controller):
address_label = AddressLabel()
orders_selected = [['1', 'Test Name', '2021-03-12', 'Status', '£200']]
scenario_one_address = ['Test First Name Test Last Name', 'Test Line One', 'Test City']
address_label_contents = address_label.create_address_label(
orders_selected)
assert address_label_contents == (scenario_one_address, 1, 0)
In any case, if anyone had any good resources to learn this from that'd be great - I've read a lot of tutorials but they all use such elementary examples that don't apply to a lot of my use cases...
Thank you in advance!

Python create instance of class using string manipulation

I wrote Class and created two lists. The first for the users and the second for the user-attributes.
I would now like to loop trough the two lists in order to create multiple Class instances with the respective data.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
emp_1 = Employee('Corey', 'Schafer', '50000')
emp_2 = Employee('Test', 'User', '60000')
by printing print(amp_1.email) i can create the instance of the class:
will print
Corey.Schafer#company.com
Now i dont want to write it out manually so i want to loop trough it:
for user in users:
for user_atr in user_atrs:
print(user + '.' + user_atr)
will print:
empy_1.first
empy_1.last
empy_1.pay
empy_1.email
empy_2.first
empy_2.last
empy_2.pay
empy_2.email
Instead of:
Corey
Schafer
50000
Corey.Schafer#email.com
Test
User
60000
Test.User#email.com
How can i use that loop to actually create the instance of the class and not just the blueprint?
Basic Solution
a list of string of the users : ['emp_1', 'emp_2']
a list of string that are attributs name ['first', 'last', 'pay', 'email']
Then use the builtin method globals() to get the variable and getattr(obj, name, default) but that isn't nice and requires to type variable names
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', '60000')
for user in ['emp_1', 'emp_2']:
for user_atr in ['first', 'last', 'pay', 'email']:
print(getattr(globals()[user], user_atr))
Better Solution
a list of Employee instances : [emp_1, emp_2]
Access object properties with __dict__ (key is name, value are property's value)
for user in [emp_1, emp_2]:
for user_atr in user.__dict__.values():
print(user_atr)
Corey
Schafer
50000
Corey.Schafer#company.com
...
To read both name and value at the same time
for user in [emp_1, emp_2]:
for user_atr in user.__dict__.items():
print(user_atr)
('first', 'Corey')
('last', 'Schafer')
('pay', 50000)
('email', 'Corey.Schafer#company.com')
...
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
emp_1 = Employee('Corey', 'Schafer', '50000')
emp_2 = Employee('Test', 'User', '60000')
users = {"emp_1": emp_1,
"emp_2": emp_2}
for user in users.values():
for attribute in list(user.__dict__.keys()):
print(f"{name}.{attribute}")
This will do that for you by storing the users in a dictionary with the name of the user as the dictionary key and then using the __dict__ attribute from the Employee class to get a dictionary of all atributes and then printing the name of each attribute from that dictionary.
If you are trying to print the value of each of these attributes then it can be changed to the following:
users = {"emp_1": emp_1,
"emp_2": emp_2}
for name, user in users.items():
for attribute in list(user.__dict__.keys()):
print(getattr(user,attribute))
Using this method means that any more attributes added to the employee class will be printed also.

Categories