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.
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:
How can I call a function within a class?
(2 answers)
Closed 3 years ago.
Apologies if the following question has already been posed on StackOverflow, but I couldn't find it posted here, nor was I able to find an answer after some time spent Googling.
My question is as follows. I would expect the following Python code,
class MNL(object):
def load_data():
r = 3 + 4
return r
def load_data_wrapper():
s = load_data()
return s
to return the output "7". Instead I get the error message "NameError: name 'load_data' is not defined".
If I change the second-to-last line to "s = self.load_data()" I get "NameError: name 'self' is not defined". For reference, I'm using Python 3.6.5.
Any help would be very much appreciated!
Any reference to object methods or attributes in Python requires the self keyword, and it should always be the first parameter of any class method. To fix your code, it would be:
class MNL(object):
def load_data(self):
r = 3 + 4
return r
def load_data_wrapper(self):
s = self.load_data()
return s
The self parameter receives the reference of the object.
Based on the questions I see in the comments I wanted to offer up some changes to the code.
class MNL(object):
#staticmethod
def load_data():
r = 3 + 4
return r
#classmethod
def load_data_wrapper(cls):
s = cls.load_data()
return s
def load_data_wrapper2():
return MNL.load_data()
This utilizes Class and Static methods These do not operate on "self" but are methods that you still want to tie to a singular class
>>> MNL.load_data_wrapper2()
7
>>> MNL.load_data_wrapper()
7
This question already has answers here:
Functions, Callable Objects, and how both are created in Python
(2 answers)
Closed 5 years ago.
class Adder:
def __call__(self, x, y):
return x + y
add1 = Adder()
def add2(x, y):
return x + y
What's the difference between add1 and add2 other than the type?
In your super-simple example. there's no practical difference, since functions are also callable objects.
However, a callable object is an object of a class that you write, so you may write this code:
class Counter:
def __init__(self, value = 0):
self.n = 0
def __call__(self):
self.n += 1
return self.n
def __repr__(self):
return str(self.n)
redWins = Counter()
blueWins = Counter()
if foo():
redWins()
else:
blueWins()
print("Red has won {} times.\nBlue has won {} times."
.format(redWins, blueWins))
And you'll find it hard to implement such a class using only functions. Even if you try to do it with global variables, you can't have separate instances of one single global variable.
See more: Functions, Callable Objects, and how both are created in Python
In your example, there's no functional difference but since add1 is an object, you can store information in the members:
class Adder:
def __init__(self):
self.__memory = 0
def __call__(self, x, y):
self.__memory += x
return x+y+self.__memory
add1 = Adder()
print(add1(10,10))
print(add1(10,10))
you get 30 then 40. You can do that with a function, but then you need a global variable, and using global variables is really asking for trouble.
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.