This question already has answers here:
How can I get the name of an object?
(18 answers)
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
im learning to make an organizational chart using class
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
abcde = employee("Elon Musk", "CEO",1000000)
print(employee.self) --> error
Basically what im trying to do is to get the "abcde" value, to use it on my other function..
is there anyway to get the name assigned to the object? in this case "abcde"
Recreating this post to clarify what im trying to do:
I simplified the complete code that i have here, but basically what im trying to do here is getting the assigned class name, in this case "abcde".
i understand that self.name will get me "elon musk:
self.title will get me "CEO"
but how do i get the "abcde"?
why do i need the abcde?
because i need to append the abcde to a list called
direct_report_list= []
to append the "abcde" inside this list, which i will use for this:
def __str__(self):
otheremp_list = []
print(self.title,” – “, self.name)
print(“Direct Reports:”)
for emp in self.direct_reports_list:
print(emp.title,” – “,emp.name)
otheremp_list.append(emp.direct_reports_list)*
print(“other employees:”)
for emp in otheremp_list:
print(emp.title,” – “,emp.name)
otheremp_list.append(emp.direct_reports_list)*
i need the "abcde" value so i can add this value into my list, which i use for the "emp" in str
override the __str__method and return a string & to get each value use object + dot + the data which you want to access
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
def __str__(self):
return self.name + "-" + self.title + "-"+ str(self.salary)
abcde = employee("Elon Musk", "CEO",1000000)
print(abcde)
#to get each value
print(abcde.name)
print(abcde.title)
print(abcde.salary)
Output:
$ python3 print.py
Elon Musk-CEO-1000000
Elon Musk
CEO
1000000
Looks like you have just started learning classes. I will try to clarify a few aspects that i think may be causing this confusion.
Remember a self keyword for a class is relevant only inside the class to refer to its own objects, and that is why you were able to use self.title in the class
When you create an object abcde you already have the object named abcde; you do not need to refer to it as employee.self.
Hence if you simply want to pass that as an object just pass by what it is actually named i.e. just abcde. Below code may make it more clear!
class employee:
def __init__(self, name , title, salary):
self.name = name
self.title = title
self.salary = salary
def simplefunc(obj):
print(obj.name)
abcde = employee("Elon Musk", "CEO",1000000)
#print(employee.self) --> Causes an Error
print(abcde)
simplefunc(abcde)
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)
How would I find a book in the "self.book_list" using the book_id and then return the book object?
class Book:
def __init__(self, number, title, author, genre, price):
self.number = number
self.title = title
self.author = author
self.genre = genre
self.price = price
book_id = int(input("Enter Book ID: "))
class Inventory:
book_list = []
def __init__(self):
self.book_list.append(Book('Science: A Visual Encyclopedia', 1000))
self.book_list.append(Book('My First Human Body Book', 1001))
self.book_list.append(Book('The Runaway Children', 1002))
self.book_list.append(Book('The Tuscan Child', 1003))
self.book_list.append(Book('Learning Python', 1004))
def display_books_in_inventory(self):
for x in self.book_list:
print (x)
def find_book_in_inventory(self, book_id):
Assuming a Book() will have an attribute called .number with its identifier:
def find_book_in_inventory(self, book_id):
return next(book for book in self.book_list if book.number == book_id)
In the comments, people were asking for the definition of Book() because it was unclear what the identifier attribute would be called exactly.
The Book class you included is still clearly not the same you're using in the construction of the list, as Book('Science: A Visual Encyclopedia', 1000) only has two parameters, while Book.__init__() has 5 required parameters, where we can only assume number is the identifier.
You need to fill the other required args in Book as they do not have a value. Parameters without a default value are required, if you don't define them while calling the class, you will get an error. Secondly, for the number arg in Book, you gave it a string instead, and for the title arg in Book you put an int. I'm pretty sure these were mistakes and you mixed up title and number. Thirdly, as the Book class is, putting it into a list isn't going to get you any good information about the Book class and its params, it's just going to give you the default string representation of the class, which is <__main__.Book object at [idk what this is]>. To fix this, you will have to put __str__() or __repr__() in your book class. Fourthly, there are no variables in the class Inventory other than book_list, you can't access anything else, in this case, it would be very useful to use variables for the books you are putting into the book_list list to access attributes of the books. Fifthly, there is no book id anywhere, you need that to get your book object. Finally, to answer your original question, you can't, you can only do that using dictionaries ({<book-id>: <book-object>}), not lists. However, one way to achieve what you are trying to do is to have the number arg as an index for book_list to get the book object you are trying to access. Final code:
class Book:
def __init__(self, title, book_id, author=None, genre=None, price=None):
self.book_id = book_id
self.title = title
self.author = author
self.genre = genre
self.price = price
class Inventory:
def __init__(self, Book: Book):
self.book_dict = {}
self.book = Book
self.book_dict.update({str(Book.id) : Book.title})
def display_books(self):
for x in self.book_dict:
print(self.book_dict[x])
def find_book_by_id(self, book_id):
return self.book_dict[str(book_id)]
This question already has answers here:
Using the class as a type hint for arguments in its methods [duplicate]
(3 answers)
Closed 5 years ago.
Let's say that I have created a class defined below, and I have called methods on it:
class Student:
def __init__(self, name):
self.name = name
self.friends = []
def add_friend(self, new_friend: Student):
self.friends.append(new_friend)
student1 = Student("Brian")
student2 = Student("Kate")
student1.add_friend(student2)
The method add_friend has a parameter called new_friend, which is a Student object. How do I use type hints to specify that? I assumed that you just have to simply enter the name of the class, like new_friend: Student but it does not work. When I run it, I get a NameError: name 'Student' is not defined. I also tried new_friend: __main__.Student, but it gives me the same error. What am I doing wrong?
Per PEP-484, use the string name of the class for forward references:
class Student:
def __init__(self, name):
self.name = name
self.friends = []
def add_friend(self, new_friend: 'Student'):
self.friends.append(new_friend)
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)
If I am creating a class below, can someone please explain the proper way to create the instance and also pass in the arguments. I though that I would be able to pass in the initial arguments at time of initiation but cannot seem to get this to work. Below is an example of the class:
Class Course(object):
"""
Represents a University course
"""
def _init_(self, name, teacher, description):
self.name = name
self.teacher= price
self.description = description
def _str_(self):
return "{name} ({desc}): {teacher:}".format(name=self.name,
desc=self.description, teacher=self.teacher)
So in my program I'd like to create an instance which I though I do by using something like class = Course().
But isn't there a way to initiate the 3 variables at the same time? Something along the lines of class('Math101', 'Dr. Know Nothing', 'Learning is Fun') ?
Then I can just print class and get my desired output string as defined from within the class? I might be missing an import somewhere which is also confusing to me if I need to import modules or with a class all I need to do is the initial class = Course() ?
You have to declare special methods with double underscores: __init__, not _init_. And then, when creating an object, you have to pass the arguments like: course1 = Course(...parameters...):
class Course(object):
"""
Represents a University course
"""
def __init__(self, name, teacher, description):
self.name = name
self.teacher = teacher
self.description = description
def __str__(self):
return "{name} ({desc}): {teacher:}".format(name = self.name,
desc = self.description, teacher = self.teacher)
course1 = Course('Math101', 'Dr. Know Nothing', 'Learning is Fun')
print course1
Output:
Math101 (Learning is Fun): Dr. Know Nothing
Notes:
The Python keyword to create a class is class, not Class. Python is case-sensitive for keywords.
You were assigning price to self.teacher, which would lead in an error because price is not declared anywhere. I think it's just a typo. You may use self.teacher = teacher instead.
You must not use Python keywords (reserved names) as name of variables, because if you did, you would be hiding those keywords, which would lead into problems.
First things first, you need to double your underscores:
def __init__(self, ...):
// whatever
def __str__(self, ...):
// whatever
and lowercase your Class: class Course instead of Class Course.
Now you can use your class like this:
course = Course('Math101', 'Dr. Know Nothing', 'Learning is Fun')
print course