Printing __init__ object from list Python error [duplicate] - python

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 4 years ago.
I am trying to print an object from a list based on my class settings.
from math import *
import time
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
people = [MyClass("David",17),
MyClass("George",63),
MyClass("Zuck",12),
MyClass("Mark",18)
]
print(people[2])
But it prints out this: <main.MyClass object at 0x0000000003129128>
I want it to print "Zuck"

That's because your array contains objects, so when you print them, they are printed as an object representation. I realize that what you want is to print its content.
For that you have to specify how you want to present the instance when printed, using the method __str__:
from math import *
import time
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "name: {}, age: {}".format(self.name, self.age)

Related

Creating classes dynamically in python [duplicate]

This question already has answers here:
How can I dynamically create derived classes from a base class
(4 answers)
Closed 10 months ago.
Is it a good coding practice to have the class name as variable.
E.g
def create_class(class_name):
class class_name:
def __init__(self):
do_sth....
class_instance = class_name()
return class_instance
for object in objects:
res = create_class(object)
I wanted to create different classes which are present in a list like objects=[person,vehicle, location ..]. What could be other alternative way to do it ?
class_name is a class, you can set a name property for your class, like this:
class class_name:
def __init__(self,name):
self.name = name
def __str__(self):
return str(self.name)
objects=["person","vehicle","location"]
for obj in objects:
res = class_name(obj)
print(res)

Get the variable value of assigned class [duplicate]

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)

How to print variable values instead of memory allocation in python [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 1 year ago.
I have coded a class that stores a name string and an int ratings ("John", 6) and stored it in a list "teams = []"
class player():
def __init__(self, name, rating):
self.name = name
self.rating = rating
teams = []
teams.append(player("juanma", 6))
teams.append(player("pablo", 7))
teams.append(player("gon", 5))
teams.append(player("pep", 4))
I have then used the combinations tool from itertools and I am trying to get it to print all the possible combinations. The problem is that it is printing the memory allocation instead of the variables.
comb = combinations(teams, 2)
for i in comb:
print(i)
This is the output that I get:
(<__main__.player object at 0x7fc4999698b0>, <__main__.player object at 0x7fc499969610>)
(<__main__.player object at 0x7fc4999698b0>, <__main__.player object at 0x7fc499999e20>)
(<__main__.player object at 0x7fc4999698b0>, <__main__.player object at 0x7fc499a015e0>)
(<__main__.player object at 0x7fc499969610>, <__main__.player object at 0x7fc499999e20>)
(<__main__.player object at 0x7fc499969610>, <__main__.player object at 0x7fc499a015e0>)
(<__main__.player object at 0x7fc499999e20>, <__main__.player object at 0x7fc499a015e0>)
YOU have to provide this.
class player():
def __init__(self, name, rating):
self.name = name
self.rating = rating
def __str__(self):
return "<player {} {}>".format(self.name,self.rating)
You need to define an __repr__ or __str__ internal function for your player class:
class player():
def __init__(self, name, rating):
self.name = name
self.rating = rating
def __str__(self):
return self.name # Or any other string representation
You can find a nice explanation of the difference between these two methods here: What is the difference between __str__ and __repr__?
You need to add a .__str__() method on your class:
def __str__(self):
return "Name: " + self.name + " Rating: " + str(self.rating)

Un-Wrap or De-Inherit an object [duplicate]

This question already has answers here:
How do I call a parent class's method from a child class in Python?
(16 answers)
Closed 1 year ago.
A code block I do not have access to, returns an object that is "wrapped" or rather inherited from a base class, that I want to recover. The wrapper is harmful, I want to get rid of it. Is there a way to upcast to the parent class? To unwrap the object? To disinherit it?
I prepared a simple example: Is it possible to manipulate the u object in a way that it will be a Person object and say hello in a nice way?
class Person():
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hi, my name is " + self.name)
class Unfriendly_Person(Person):
def say_hello(self):
print("Leave me alone!")
u = Unfriendly_Person("TJ")
u.say_hello()
You might assign to __class__, so
class Person():
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hi, my name is " + self.name)
class Unfriendly_Person(Person):
def say_hello(self):
print("Leave me alone!")
u = Unfriendly_Person("TJ")
u.__class__ = Person
u.say_hello()
output:
Hi, my name is TJ
But rememeber that this will jettison all methods from Unfriendly_Person even these not defined in Person.

How to specify Type Hint for Parameters for Custom Classes? [duplicate]

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)

Categories