This question already has answers here:
Confused about __str__ on list in Python [duplicate]
(8 answers)
Closed 5 years ago.
I have a simple class I created:
class C:
def __init__(self):
self.a = 1
and I want to print a list of objects from this class using a function I created:
def p(s):
print('hi ', s)
This is how I want to call the printing function p: p([C() for i in range(3)])
Unfortunately, this produces hi [<__main__.C object at 0x000000F92A8B9080>, <__main__.C object at 0x000000F92AB0E898>, <__main__.C object at 0x000000F92AB0E978>].
I thought the problem was due to not implementing __str__ so I changed my class into:
class C:
def __init__(self):
self.a = 1
def __str__(self):
return str(self.a)
but I get the same result :(
What I hoped for was hi [1, 1, 1] or hi 1, 1, 1 or something like that, not the memory location of the objects I created.
I can use
for i in range(3):
p(C())
but I want to pass a list of objects to the p function rather than call it for each of my objects. Is that possible?
Replace __str__ with __repr__:
def __repr__(self):
return str(self.a)
Related
This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Object string representation in Python/IPython shell
(3 answers)
Closed 28 days ago.
When defining my own class, I can overwrite the __str__ to define its print(my_class) behavior. What do I have to do to overwrite the behavior when just calling an my_class object?
What I get:
> obj = my_class("ABC") # define
> print(obj) # call with print
'my class with ABC'
> obj # call obj only
'<__console__.my_class object at 0x7fedf752398532d9d0>'
What I want (e.g. obj returning the same as print(obj) or some other manually defined text).
> obj # when obj is called plainly, I want to define its default
'my class with ABC (or some other default representation of the class object)'
With:
class my_class:
def __init__(self, some_string_argument)
self.some_string = some_string_argument
def __str__(self): #
return f"my_class with {self.some_string}"
Magic method __repr__ is the one. But this is discouraged.
In general __str__ should be understandable for the end user and __repr__ should return a string which when passed to eval would produce a valid instance of the object for which it's defined.
class A:
def __repr__(self):
return "I'm A!"
a = A()
a # This will print "I'm A!"
What it should/could be:
class A:
def __repr__(self):
return "A()"
a = A()
a_repr = a.__repr__()
b = eval(a_repr) # "b" is an instance of class A in this case
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)).
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.
This question already has answers here:
What are metaclasses in Python?
(25 answers)
Closed 7 years ago.
I know we can overload behavior of instances of a class, e.g. -
class Sample(object): pass
s = Sample()
print s
<__main__.Sample object at 0x026277D0>
print Sample
<class '__main__.Sample'>
We can change the result of print s:
class Sample(object):
def __str__(self):
return "Instance of Sample"
s = Sample()
print s
Instance of Sample
Can we change the result of print Sample?
You can use a metaclass:
class SampleMeta(type):
def __str__(cls):
return ' I am a Sample class.'
Python 3:
class Sample(metaclass=SampleMeta):
pass
Python 2:
class Sample(object):
__metaclass__ = SampleMeta
Output:
I am a Sample class.
A metaclass is the class of class. Its relationship to a class is analogous to that of a class to an instance. The same classstatement is used. Inheriting form type instead from object makes it a metaclass. By convention self is replaced by cls.
This question already has answers here:
Class (static) variables and methods
(27 answers)
Closed 8 years ago.
Is it possible in Python make a static attribute of class which will be same for all instances (objects) of that class, they all will use same reference to that attribute without creating their own attributes.
For example :
class myClass:
__a = 0
def __init__(self, b, c):
self.b = b
self.c = c
def increase_A(self):
self.__a += 1
return
def get_A(self):
return self.__a
So if I have
myObject1 = myClass(1,2)
myObject2 = myClass(3,4)
myObject2.increase_A()
print myObject1.get_A()
will show one and not zero, couse they share the same variable ?
To make your code work as it appears you intend, use myClass.__a to access the variable, instead of self.__a.
def increase_A(self):
myClass.__a += 1
return
def get_A(self):
return myClass.__a
They start off as the same variable. However, when you do
self.__a += 1
this rebinds the object's __a to a new object whose value is 1.
It does not change any other object's __a so the code will print out 0.