I am generating a list of employees and managers. However, I obtained this weird output after trying sort them by last name (my initial class employee only contains "name" but not divide into first name and last name. Then, I use [1] to indicate the last name). What's wrong with my code since I can't see my list of employees.
class Employee:
def __init__(self, name, socialSecurityNumber, salary):
"""
Set name, socialSecurityNumber, and salary to itself.
"""
self.name = name
self.socialSecurityNumber = socialSecurityNumber
self.salary = salary
employeeList = []
employee1 = Employee("Banny Chu", "777-88-9999", 45000)
employee2 = Employee("Luffy Monkey", "555-66-9999", 32000)
employee3 = Employee("Zoro Nonoroa", "222-00-3333", 37000)
manager1 = Manager("Scalt Haight", "444-33-1111", 60000, "Lab", 2300)
manager2 = Manager("Kapu Ro", "333-44-2222", 65000, "General", 2600)
manager3 = Manager("Nami Swan", "111-77-6666", 80000, "HR", 3000)
employeeList.append(employee1)
employeeList.append(employee2)
employeeList.append(employee3)
employeeList.append(manager1)
employeeList.append(manager2)
employeeList.append(manager3)
print (sorted(employeeList, key=lambda employee: employee.name[1].lower()))
Output as below (strange output since I can't see my employeeList in the correct format even though I type print(employeeList) and gave the same format as below.
[<employee8.Employee object at 0x105a48b00>, <manager8.Manager object at 0x1054290f0>, <manager8.Manager object at 0x1054290f0>, <manager8.Manager object at 0x1054290f0>, <manager8.Manager object at 0x1054290f0>]
What should I modify it so that I can see my sorted list in the way that I can clearly see them?
By default, user-defined objects will be represented as a class instance at a location in memory:
<__main__.Employee instance at 0x02A39940>
You will need to add a special method for object representation in your Employee class:
class Employee:
def __init__(self, name, socialSecurityNumber, salary):
"""
Set name, socialSecurityNumber, and salary to itself.
"""
self.name = name
self.socialSecurityNumber = socialSecurityNumber
self.salary = salary
def __repr__(self):
return self.name # represents object with name
You're missing the point that sorted returns a permutation of the list that got sorted based on the criteria you sent it. It doesn't automagically return just the keys you sorted them on if that's what you were expecting?
sort = sorted(employeeList, key=lambda employee: employee.name[1].lower())
print([emp.name.split()[1] for emp in employeeList])
Output (I was lazy and only copy pasted 3 of your employees):
['Chu', 'Monkey', 'Nonoroa']
You were also missing a split, because you save your name in a single string. Indexing a single string will return a single character at that location in a string.
If your goal wasn't to print out just the last names, then you have to override either the __str__ or __repr__ method. (Read about what exact difference is between the methods here.)
You forgot to split the name in the key function: employee.name.split(' ')[1].
Python calls __repr__ on the sorted list which prints '[' and ']' at the beginning and end and then calls __repr__ on each list element. The default __repr__ prints the object type and address. If you want to see something else, you have to give python another __repr__ to call.
class Employee:
def __init__(self, name, socialSecurityNumber, salary):
"""
Set name, socialSecurityNumber, and salary to itself.
"""
self.name = name
self.socialSecurityNumber = socialSecurityNumber
self.salary = salary
def __repr__(self):
return "{} {} {}".format(self.name, self.socialSecurityNumber, self.salary)
class Manager(Employee):
def __init__(self, name, socialSecurityNumber, salary, department, unknown):
super().__init__(name, socialSecurityNumber, salary)
employeeList = []
employee1 = Employee("Banny Chu", "777-88-9999", 45000)
employee2 = Employee("Luffy Monkey", "555-66-9999", 32000)
employee3 = Employee("Zoro Nonoroa", "222-00-3333", 37000)
manager1 = Manager("Scalt Haight", "444-33-1111", 60000, "Lab", 2300)
manager2 = Manager("Kapu Ro", "333-44-2222", 65000, "General", 2600)
manager3 = Manager("Nami Swan", "111-77-6666", 80000, "HR", 3000)
employeeList.append(employee1)
employeeList.append(employee2)
employeeList.append(employee3)
employeeList.append(manager1)
employeeList.append(manager2)
employeeList.append(manager3)
for employee in sorted(employeeList, key=lambda employee: employee.name.split(' ')[1].lower()):
print(employee)
Related
I'm new to python and as I was doing an assignment for class, I got stuck using init method.
class Customer(object):
def __init__(self, number, name):
self.name = name
self.number = number
self.orders = []
def addorder(self, order):
self.orders.extend(order)
return self.orders
def __str__(self):
return str(self.orders)
Customer('308','John').addorder((1,2,3,4))
print(Customer('308','John'))
The output is an empty list [].
I want the output to be [1,2,3,4]
What am I doing wrong here?
The issue is that you have two Customer objects. I.e. your print line:
print(Customer('308','John'))
Is creating a new Customer object with a number of '308' and a name of 'John'. It's completely unrelated to the customer on the previous line.
To fix this, you should assign your first object to a variable (think of it like a handle, that lets you access the object), and then print that:
john = Customer('308','John')
john.addorder((1,2,3,4))
print(john)
You're creating two instances of the class
class Customer(object):
def __init__(self, number, name):
self.name = name
self.number = number
self.orders = []
def addorder(self, order):
self.orders.extend(order)
return self.orders
def __str__(self):
return str(self.orders)
customer = Customer('308','John')
customer.addorder((1,2,3,4))
print(customer)
Keep in mind that each time you "call" a class, you instantiate a new object (this is why in many languages other than Python, this actually requires the keyword new). So, in your example, you're instantiating two different objects (that don't share their properties). Instead, you should save them in a variable:
customer = Customer("308", "John")
customer.addorder((1, 2, 3, 4))
print(customer)
I have written code to count employees using class but the the code doesn't work.
class employee:
empCount = 0;
def employee(self, name, salary):
self.name = name;
self.salary = salary;
employee.empCount += 1;
def displayCount(self):
print ("\nTotal Employee %d", Employee.empCount);
def displyEmployee(self):
print('Name:',self.name,'Salary:',self.salary);
emp1 = employee('ABS', 2000)
Your code has a number of problems that are preventing it from working as you expect:
You did not declare your constructor properly. When you do employee('ABS', 200), Python looks for a function called __init__ on the class object. You declared your constructor as employee, similarly to how you would do so in C-based languages. This won't work.
You store the employee count as a variable scoped to the class object. You can do this but I wouldn't because it's a misuse of that capability. Instead, you should create a list of employees and get the length of the list.
Instead of declaring display functions, you should overload the __str__ function, which returns a string representing the object.
Class names should be PascalCase (this doesn't keep your code from working but you should definitely address it).
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def __str__(self):
return f"Name: {self.name}, Salary: {self.salary}"
employees = []
employees.append(Employee('ABS', 200))
len(employees) # 1
I have an class Student which has an array(list) of Objects called Students. I am trying to output the names of all the students in the array.
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
Students = []
Students.append(Student("Dave",23,"Chem"))
Students.append(Student("Emma",34,"Maths"))
Students.append(Student("Alex",19,"Art"))
print(Students[0].__dict__)
print(Students[1].__dict__)
print (Students[0])
Both the ways I have found and tired do not output the specific name but the location or the whole object. Is there a way to just output the name? For example output Students[0] name Dave
{'name': 'Emma', 'age': 34, 'major': 'Maths'}
<__main__.Student object at 0x000001FCDE4C2FD0>```
If you just want the name, you can print(Students[0].name). If you want to see the relevant attributes when printing a Student object, you can implement the __repr__ method.
class Student:
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def __repr__(self):
return f"<Student name={self.name} age={self.age} major={self.major}>"
This way you can simply do print(Students[0]) to see the name, age and major of a student.
By the way, for a normal class definition, you want to initialize instance attributes inside the __init__ method, instead of declaring them above __init__: those are class attributes. Please read this section of the documentation to familiarize yourself with the syntax.
For a project that I am working on, I need to convert a string (which has ID numbers (ie ID_00000001...ID_00002032 or something like that)) into a class.
By that I mean, there is already a class stored that has values like so:
class ID_00000001:
name = 'Robert Johnson'
age = 193
facebook_url = 'facebook.com/Robert_johnson'
etc.
I want to make it so that I can compare this profile to others. The way I was thinking of doing this was comparing values like (psudo):
current_profile_str = 'ID_00000001'
for i in range(len(all_IDs)):
matches = []
num = *converts number into 8 digit str*
cycle_profile_str = 'ID_' + num
*convert current_profile and cycle_profile to class*
if (current_profile.age == cycle_profile.age):
matches.append(cycle_profile_str)
So the question that I suppose I have in this context, is how would I be able to convert a string to a class?
You are using classes wrongly. You have one class, a facebook user.
This could look like this:
class FacebookUser():
def __init__(self, id, name, age, url):
self.id = id
self.name = name
self.age = age
self.url = url
You can then create instances for each user.
user1 = FacebookUser(1, 'John Doe', 27, 'facebook.com/john_doe')
user2 = FacebookUser(3, 'Jane Doe', 92, 'facebook.com/jane_doe')
print(user1.age == user2.age)
To represent a class as a string, you can add the __repr__ magic function to the class:
class FacebookUser():
def __init__(self, id, name, age, url):
self.id = id
self.name = name
self.age = age
self.url = url
def __repr__(self):
return 'FacebookUser(id: {:08d}, name: {}, age: {})'.format(
self.id,
self.name,
self.age,
)
This will result in
>>> print(user1)
FacebookUser(id: 00000001, name: John Doe, age: 27)
For the other way around, you would implement an alternative constructor using
a class method. These are methods belonging to a class, not to the instance.
The first argument in these functions is the class cls, not the instance self:
class FacebookUser():
def __init__(self, id, name, age, url):
self.id = id
self.name = name
self.age = age
self.url = url
def __repr__(self):
return 'FacebookUser(id: {:08d}, name: {}, age: {})'.format(
self.id,
self.name,
self.age,
)
#classmethod
def from_string(cls, string):
'''
Create a new instance from a string with format
"id,name,age,url"
'''
_id, name, age, url = string.split(',')
return cls(int(_id), name, int(age), url)
user1 = FacebookUser.from_string('1,John Doe,27,facebook.com/john_doe')
MaxNoe's answer is probably what you're looking for, but anyway...
If you really, actually want to somehow build up a class from a sequence of strings (For example, to have variables with their names extracted from the string itself, then you might want to look at metaclasses.
http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/
I'm trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances.
I can't seem to understand this practice problem:
Create and return a student object whose name, age, and major are
the same as those given as input
def make_student(name, age, major)
I just don't get what it means by object, do they mean I should create an array inside the function that holds these values? or create a class and let this function be inside it, and assign instances? (before this question i was asked to set up a student class with name, age, and major inside)
class Student:
name = "Unknown name"
age = 0
major = "Unknown major"
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def make_student(name, age, major):
student = Student(name, age, major)
return student
Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:
class Student(object):
name = ""
age = 0
major = ""
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
# Note: I didn't need to create a variable in the class definition before doing this.
student.gpa = float(4.0)
return student
I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.
Create a class and give it an __init__ method:
class Student:
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def is_old(self):
return self.age > 100
Now, you can initialize an instance of the Student class:
>>> s = Student('John', 88, None)
>>> s.name
'John'
>>> s.age
88
Although I'm not sure why you need a make_student student function if it does the same thing as Student.__init__.
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student function by explicitly assigning the attributes to a new instance of Student -
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).
If you use that, then a make_student function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.
class Student:
def __init__(self):
# creating an object....
student1=Student()
Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..
class Student:
def __init__(self,name,age):
self.name=value
self.age=value
# creating an object.......
student2=Student("smith",25)