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.
Related
This question already has answers here:
Difference between #staticmethod and #classmethod
(35 answers)
Meaning of #classmethod and #staticmethod for beginner [duplicate]
(12 answers)
Closed 6 months ago.
I am just starting to learn about OOP in python and came across class methods. I wrote a small bit of code to make sure I understood it properly.
class Person:
no_of_people = 0
def __init__(self, name):
self.name = name
Person.add_person()
#classmethod
def add_person():
no_of_people += 1
#classmethod
def show_number():
return no_of_people
When I try to run the code it shows the error message:
TypeError: add_person() takes 0 positional arguments but 1 was given
But when I just insert an argument into the class methods, the error goes away and functions just as I intended.
class Person:
no_of_people = 0
def __init__(self, name):
self.name = name
Person.add_person()
#classmethod
def add_person(h):
h.no_of_people += 1
#classmethod
def show_number(h):
return h.no_of_people
Can someone please explain why to me?
For class method you have to give self as a parameter.
So
def add_person(h):
should be
def add_person(self , h):
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:
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
This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 7 years ago.
I mean , for example, in the following code I want to call prin in pre by name, but how?
class a(object):
def __init__(self):
self.zz=1
self.aa='hello'
def prin(self):
print 'hello'
def pre(self,name):
#if name is 'prin' then call self.prin
if __name__ == '__main__':
az = a()
az.pre('prin')`
getattr
def pre(self,name):
# name being 'prin' in your case
if hasattr(self, name):
getattr(self, name)()