Can I control how Classes called? [duplicate] - python

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
What is the difference between __str__ and __repr__?
(28 answers)
How can I choose a custom string representation for a class itself (not instances of the class)?
(7 answers)
Closed 1 year ago.
I wrote some code and was not sure how to make it work as expected,
class Bee():
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
bee = Bee(name='Bumble', identifier=1)
print(str(bee))
->> Should Print: 1 Bumble
I thought of creating a function in Class Bee as follows:
def get_hive(self):
return '{} {}'.format(self.identifier, self.name)
However, I am not sure how, when I create an object of class Bee, to assign given attributes instead of address of the memory cell.
My code currently ofc prints smth like: <main.Bee object at 0x000001EA24F49460> instead of the attributes.

If you want str(bee) to return a string as you describe, implement a __str__ method:
class Bee():
def __init__(self, name: str, identifier: int):
self.name = name
self.identifier = identifier
def __str__(self) -> str:
return f"{self.identifier} {self.name}"
bee = Bee('Bumble', 1)
print(bee)
prints:
1 Bumble
Note that print will automatically call str on any parameter that's not already a str, so you can just say print(bee) instead of print(str(bee)).

Related

How to print the values of objects stored in a list [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Print out objects stored in a list
(2 answers)
Closed 1 year ago.
I'm trying to iterate over User objects stored in a python list called myusers then print each. This is what I've done:
class User:
def __init__(self,name,age):
self.name = name
self.age = age
myusers= [User("Fred", "30"), User("Doe", "20")]
for i in range(2):
print(str(myusers[i]))
what I get from the above is the memory location as follows:
<__main__.User object at 0x000001FD807B4250>
<__main__.User object at 0x000001FD807F13A0>
However, I was expecting to get:
User("Fred", "30")
User("Doe", "20")
I've seen this question: https://stackoverflow.com/questions/59115308/print-out-objects-stored-in-a-list but it didn't answer my question since I'm using str in the print function. Can anyone let me know when I'm not getting this value?
As remarked in the comments, you should define a __str__ method, which defines how to represent your object as a string.
class User:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return f'User("{self.name}", "{self.age}")'
myusers= [User("Fred", "30"), User("Doe", "20")]
for i in range(2):
print(myusers[i])

What is the right way to use len() *inside* a class? [duplicate]

This question already has answers here:
Meaning of #classmethod and #staticmethod for beginner [duplicate]
(12 answers)
Closed 3 years ago.
I'm trying to figure out how len() is works when used inside Python class. Running this code results in the error shown, even though I added a __len__ overload and used #property, following various advice from the Internet.
class Routes:
def __init__(self):
self._route_list = list()
def __len__(self):
return len(self._route_list)
#property
def route_list(self):
return self._route_list
#classmethod
def check_list(self):
if not self.route_list or len(self.route_list) == 0:
print('ERROR: no items to print!')
routes = Routes()
routes.check_list()
TypeError: object of type 'property' has no len()
class Routes:
def __init__(self):
self._route_list = list()
def __len__(self):
return len(self._route_list)
def add_route(self):
self._route_list.append("route")
routes = Routes()
print(len(routes)) # 0
routes.add_route()
print(len(routes)) # 1
When you override len, you are overriding the call to len with that object as the parameter. Same thing when you overload any other of those types of methods.

Why is the <__main_.ClassName at object 0xxxxxxxx> is showing? And how to get the actual results? [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 5 years ago.
I am making a simple class, here is the code:
class Player(object):
def __init__(self, character):
self.character= character
Sara = Player("Sara")
Nothing fancy, when ever i run this it gives the following result:
>>> print Sara
<__main__.Player object at 0xxxxxxxxx>
How can i stop the last line <main.Pl.....> from executing?
You need to set the __repr__ and __str__ functions in your class so the print function knows what to print correctly. Please change your class to the example below and try again.
class Player(object):
def __init__(self, character):
self.character = character
def __repr__(self):
return self.character
def __str__(self):
return self.character

Why are instances of this class being overwritten? [duplicate]

This question already has answers here:
Meaning of #classmethod and #staticmethod for beginner [duplicate]
(12 answers)
Closed 6 years ago.
I'm programming a script with Python using instances of FileHandler class but the second overwrites the first even without being assigned to the same variables.
The class:
class FileHandler():
name = None
path = None
#classmethod
def __init__(self,name,path):
self.name=name
self.path=path
#classmethod
def getName(self):
return self.name
#classmethod
def getPath(self):
return self.path
The script:
import fileHandler
origen=fileHandler.FileHandler('a','b')
destino=fileHandler.FileHandler('c','d')
print origen.getName(),origen.getPath()
print destino.getName(),destino.getPath()
The result:
c d
c d
You are using __init__ method as a class method.
Using #classmethod for every method will result in a singleton, that's why the vars overwrite.

Get the name under which a variable or property is stored [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 6 years ago.
Is there a way to get the name under which a variable or a property is stored?
Something like:
class X:
def __init__(self):
self.name = __name_under_which_I_m_stored__
jeff = X()
print(jeff.name) # yields 'jeff'
Pretty sure that this is not possible, but you never know... Furthermore, I'm aware that the name could be unspecified (do_something(X())) or ambiguous (jeff=frank=X()).
The Python VM has no way to know the literal name of a name. For objects, you can access the name via __name__ attribute.
If you want to do this, you'll need to implement a mapping of names to values. You can do this with a dict.
class X:
def __init__(self):
self.names = {};
def set(self, name, value):
self.names[name] = value
def get(self, name):
return (name, self.names[value])
jeff = X()
jeff.set("name", "jeff");
print(jeff.get("name")) # yields ("name", "jeff")

Categories

Resources