Related
class BaseContacs:
def __init__(self, name, surname, phone, email):
self.name = name
self.surname = surname
self.phone = phone
self.email = email
#Variables
self._label_lenght = len(name) + len(surname) +1
def contact(self, ):
print(f" Wybieram numer", self.phone, "i dzwonię do", self.name, self.surname)
def __str__(self):
return f'{self.name} {self.surname} {self.phone} {self.email}'
#property
def label_lenght(self):
return self._label_lenght
class BuisnessContact(BaseContacs):
def __init__(self, position, company, company_phone, *args, **kwargs):
super().__init__(*args, **kwargs)
self.position = position
self.company = company
self.company_phone = company_phone
def buisnesscontact(self,):
print(f" Wybieram numer firmowy", self.company_phone, "i dzwonię do", self.name, self.surname, self.position, "w", self.company, "company")
kontakt1 = BaseContacs(name="Adam", surname="Nowak", phone=777666777, email="adam.nowak#op.pl")
kontakt2 = BuisnessContact(name="Stefan", surname="Jajko", phone=777667777, company_phone=727666777, email="stefan.jajko#op.pl",position="manager", company="diablo")
How can i add create_contacts function which can used faker to create random contacts?
I think it could be something like this:
def create_contacts(input):
but i don't know what's next
I have the following:
class Person:
def __init__(self, name, last_name=None, age=None):
self.name = name
self.last_name = last_name
self.age = age
def random_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
def main():
foo = Person('foo', 'food', 10)
bar = Person(['bar', 'car'], 'dar', 20)
print(random_generator(10, "6793YUIO")
if __name__ == "__main__":
main()
I76997Y37O
I want to add a random string to the first name of any object that has last_name value.
for example:
a random string will be added after the name 'foo' and another one bewtween the name 'bar' and 'car', and the result will be:
['foo', 'I76997Y37O']
['bar', 'OUO9UOUU3U', 'car']
How can I do it?
Thank you,
Matan.
from random import randrange
class Person:
def __init__(self, name, last_name=None, age=None):
self.name = name
self.last_name = last_name
self.age = age
if(last_name!=None):
try:
for i in range(0,len(self.name)-1,2):
randStr = ""
for j in range(randrange(3,8)):
randStr = randStr + chr(97+randrange(0,26))
self.name.insert(i+1,randStr)
except:
randStr = ""
for j in range(randrange(3,8)):
randStr = randStr + chr(97+randrange(0,26))
self.name = self.name + " " + randStr
def main():
foo = Person('foo', 'food', 10)
bar = Person(['bar', 'car'], 'dar', 20)
print(foo.name)
print(bar.name)
if __name__ == "__main__":
main()
I think this will solve your problem, you can change the range of characters in both the j loops.
Check this output
Here is one way to do this.
import string
import random
class Person:
def __init__(self, name, last_name=None, age=None):
self.name = name
self.last_name = last_name
self.age = age
def insert(self, str):
if self.last_name != None:
if isinstance(self.name, list):
self.name.insert(1, str)
else:
self.name = [self.name, str]
def random_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
def main():
foo = Person('foo', 'food', 10)
bar = Person(['bar', 'car'], 'dar', 20)
foo.insert(random_generator(5))
bar.insert(random_generator(5))
print(foo.name)
print(bar.name)
if __name__ == "__main__":
main()
Output:
['foo', 'VUZQR']
['bar', 'JWBAJ', 'car']
If I want that all the first names will be in square brackets, how can I preform the code?
For example:
foo = Person(['foo'], None, 10)
bar = Person(['bar', 'car', 'zbabur'], 'dar', 20)
Second question:
If I want to equalize bar.name[1] to foo.name
bar.name[1] = foo.name
print(bar.name[1])
It gives me an error:
Expected type {ne}, got 'None' instead
Still very new to python and taking an online intro class. I cannot figure out this problem from my textbook and no answer key! This chapter is on classes and I think I almost have the answer right- I'm sure it's something silly I'm just totally missing! I keep getting AttributeError: module 'employee' has no attribute 'employee.
#The class represents the employee class
class Employee:
def __init__(self, name, ID_number, department, job_title):
self.__name = name
self.__ID_number = ID_number
self.__department = department
self.__job_title = job_title
def set_name(self,name):
self.__name = name
def set_ID_number(self, ID_number):
self.__ID_number - ID_number
def set_department(self, department):
self.__department = department
def set_job_title(self, job_title):
self.__job_title = job_title
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID-number
def get_department(self):
return self.__department
def get_job_title (self):
return self.__department
import employee
def main():
#create 3 instances of Employee objects
SM_info = employee.employee ('Susan Meyers', '47899', 'Accounting', 'Vice President')
MJ_info = employee.employee ('Mark Jones', '39119', 'IT', 'Programmer',)
JR_info = employee.employee ('Joy Rogers', '81774', 'Manufacturing', 'Engineer')
#print the employee objects
print('Employee 1: ')
display_employee(SM_info)
print()
print('Employee 2: ')
display_employee(MJ_info)
print()
print('Employee 3: ')
display_employee(JR_info)
def display_employee(employee):
print('Name: ', employee.get_name())
print('ID Number: ', employee.get_ID_number())
print('Department: ', employee.get_department())
print('Job Title: ', employee.get_job_title())
#call the main function
main()
When you're trying to create an employee, you're calling employee.employee. That's the attribute that doesn't exist.
You need to create an employee object like this:
SM_Info = Employee( 'Mark Jones', '39119', 'IT', 'Programmer',)
hoping Employee class is in employee.py file. then CODE is as
#The class represents the employee class # employee.py
class Employee:
def __init__(self, name, ID_number, department, job_title):
self.__name = name
self.__ID_number = ID_number
self.__department = department
self.__job_title = job_title
def set_name(self,name):
self.__name = name
def set_ID_number(self, ID_number):
self.__ID_number - ID_number
def set_department(self, department):
self.__department = department
def set_job_title(self, job_title):
self.__job_title = job_title
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID_number
def get_department(self):
return self.__department
def get_job_title (self):
return self.__department
# main.py
from employee import Employee
def display_employee(employee):
print('Name: ', employee.get_name())
print('ID Number: ', employee.get_ID_number())
print('Department: ', employee.get_department())
print('Job Title: ', employee.get_job_title())
def main():
#create 3 instances of Employee objects
SM_info = Employee('Susan Meyers', '47899', 'Accounting', 'Vice President')
MJ_info = Employee('Mark Jones', '39119', 'IT', 'Programmer',)
JR_info = Employee('Joy Rogers', '81774', 'Manufacturing', 'Engineer')
#print the employee objects
print('Employee 1: ')
display_employee(SM_info)
print()
print('Employee 2: ')
display_employee(MJ_info)
print()
print('Employee 3: ')
display_employee(JR_info)
#call the main function
main()
So I got my code to work, but two lines are messing me up, and not quite sure what to put.
Code(the two lines are marked):
class Person(object):
numPerson = 0
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
def fullName(self):
print self.firstName +' '+self.lastName
class Employee(Person):
numEmployee = 0
def __init__(self,firstName,lastName,pay,employID):
Person.__init__(self, firstName, lastName)
self.pay = pay
self.employID = employID
Employee.numEmployee += 1
class Programmer(Employee):
def __init__(self,firstName,lastName,pay,employID,proLang):
self.proLang = proLang
Employee.__init__(self, firstName, lastName, pay, employID)
class Manager(Employee):
def __init__(self,firstName,lastName,pay,employID,progList):
self.progList = progList
Employee.__init__(self, firstName, lastName, pay, employID)
def addProgrammer(self):
self.progList.append(Programmer.fullName) <------------------- This line
def removeProgrammer(self):
if len(self.progList) == 0:
pass
else:
del self.progList[0]
def printList(self):
print self.progList
a = Manager('Alfred','Jones',20.00,0001,[])
b = Programmer('James','Smith', 11.75, 0002, 'Java')
a.addProgrammer() <--------------------------------------------- And This line
a.printList()
I'm trying to add the programmer's name to the progList using the .addProgramer method. I keep trying different combos and this is the closest I got.
Output:
[<unbound method Programmer.fullName>]
So, I'm not sure what needs to be in the addProgramer method in order to properly add the programmers name, or if I need an argument inside the a.addProgrammer at the very end.
Here:
self.progList.append(Programmer.fullName)
You're not adding an instance of a programmer, you are adding a method from the programmer class.
Also:
def fullName(self):
print self.firstName +' '+self.lastName
This doesn't actually return the name of the programmer, it only prints it to the console. To actually output and use the the fullname you need to return self.firstName + ' ' + self.lastName
Likewise in that function you also need to specify which programmer you are adding:
def addProgrammer(self, added_programmer):
self.progList.append(added_programmer.fullName()) # Call the function to get the fullname
And now to add a programmer:
Alfred = Manager('Alfred','Jones',20.00,0001,[]) #make a manager
James = Programmer('James','Smith', 11.75, 0002, 'Java') #make a programmer
Alfred.addProgrammer(James) #add the programmer
Alfred.printList()
Putting this all together:
class Person(object):
numPerson = 0
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
def fullName(self):
return self.firstName +' '+self.lastName
class Employee(Person):
numEmployee = 0
def __init__(self,firstName,lastName,pay,employID):
Person.__init__(self, firstName, lastName)
self.pay = pay
self.employID = employID
Employee.numEmployee += 1
class Programmer(Employee):
def __init__(self,firstName,lastName,pay,employID,proLang):
self.proLang = proLang
Employee.__init__(self, firstName, lastName, pay, employID)
class Manager(Employee):
def __init__(self,firstName,lastName,pay,employID,progList):
self.progList = progList
Employee.__init__(self, firstName, lastName, pay, employID)
def addProgrammer(self, added_programmer):
self.progList.append(added_programmer.fullName()) # Call the function to get the fullname
def removeProgrammer(self):
if len(self.progList) == 0:
pass
else:
del self.progList[0]
def printList(self):
print self.progList
Alfred = Manager('Alfred','Jones',20.00,1,[])
James = Programmer('James','Smith', 11.75, 2, 'Java')
Alfred.addProgrammer(James)
Alfred.printList()
Here is the whole program. I'm not sure why but the error says this but I am using a seperate .py program to test all the functions within this class and I ran into this error that I can't seem to find a solution to.
File "C:\Python\PythonLab\PythonLab.py\classes.py", line 73, in
printEmployeeNames
Supervisor.printName(worker) File "C:\Python\PythonLab\PythonLab.py\classes.py", line 56, in printName
print(str(self.name) + "'" + str(self.department)) AttributeError: 'str' object has no attribute 'name'
class Employee:
def __init__(self, fullname, datestart, monthstart, yearstart):
self.fullname = fullname
self.datestart = datestart
self.monthstart = monthstart
self.yearstart = yearstart
def getService(self):
from datetime import date
current_date = date.today()
date1 = date(self.yearstart, self.monthstart, 1)
date_now = date(current_date.year, current_date.month, 1)
serviceTime = date_now - date1
day_format = serviceTime.days
years = int((day_format/365))
months = int(((day_format % 365)/30))
if day_format < 0:
return('Still In Service')
if day_format == 1:
return("Last Service Time was Yesterday")
if day_format < 365:
return("Last Service Time was " + str(months) + " months ago.")
if day_format > 365:
return('Last Service Time was ' + str(years) + "-" + str(months) + " ago.")
def printName(self):
print(self.fullname)
def setName(self, name):
self.fullname = name
class Supervisor(Employee):
def __init__(self, name, datestart, department):
Employee.__init__(self, name, int(datestart[0:2]), int(datestart[2:4]), int(datestart[5:8]))
self.employees = {}
self.contact_info = {}
self.department = department
self.name = Employee.__name__
def getName(self):
return self.fullname
def printName(self):
print(str(self.name) + "'" + str(self.department))
def setName(self, name, department):
self.name = name
self.department = department
def addEmployee(self, Employee):
self.employees[str(Supervisor.getName(self))] = Employee
def isManager(self):
if self.employees:
return True
else:
return False
def printEmployeeNames(self):
for worker in self.employees:
Supervisor.printName(worker)
def removeEmployee(self, employeename):
for worker in self.employees:
if employeename in self.employees:
del self.employees[employeename]
def getContactInfo(self):
return self.employees
def setContactInfo(self, phone, fax, email):
self.contact_info["phone"] = phone
self.contact_info["fax"] = fax
self.contact_info["email"] = email
def getPhone(self):
return self.contact_info["phone"]
def getFax(self):
return self.contact_info["fax"]
def getEmail(self):
return self.contact_info["email"]
self.employees is a dict. Iterating it means iterating its keys. Thus, in this code
for worker in self.employees:
Supervisor.printName(worker)
worker is a string. Change it to:
for worker in self.employees:
Supervisor.printName(self.employees[worker])
Or, even more to the point:
for name, worker in self.employees.items(): # iterates key-value pairs
Supervisor.printName(worker)