Why is the staticmethod decorator necessary? [duplicate] - python

This question already has answers here:
Does the #staticmethod decorator do anything?
(2 answers)
Closed 3 years ago.
Given that the following code runs without error, why is the staticmethod decorator necessary? What is it actually doing?
class Foo:
def say_hi(name):
print(f'Hello {name}.')
#staticmethod
def say_bye(name):
print(f'See ya later, {name}.')
my_name = 'Bar...t'
Foo.say_hi(my_name)
Foo.say_bye(my_name)

Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
The difference between a static method and a class method is:
Static method knows nothing about the class and just deals with the parameters.
Class method works with the class since its parameter is always the class itself.
https://www.programiz.com/python-programming/methods/built-in/staticmethod

Related

Method vs function-valued field in Python [duplicate]

This question already has answers here:
What is the difference between a function, an unbound method and a bound method?
(6 answers)
Closed 2 years ago.
I am switching from MATLAB to Python and numpy and I would like to know if there is any difference between the option to define a class method and the option to the function to a class field (instance variable)? Here is the example:
class MyClass:
def __init__(self, a):
self.a=a #some variable
def add(self,b):
return self.a+b
vs
class MyClass:
def __init__(self, a):
self.a=a #some variable
self.add = lambda b: self.a+b
It works in both cases when I call
my_object=MyClass(2)
print(my_object.add(2)) #prints 4
Are there any differences between these two approaches? Any best practices/downsides?
To me, the first one feels more "proper OOP", but the second one feels more flexible. Or, maybe, the definitions are identical, because of the way Python works under the hood?
The second one can't be overridden and takes a lot more space, because there's a separate function in every instance's __dict__ instead of one function in the class __dict__. (Instance method objects are created and reclaimed on the fly if you do it the normal way, or optimized out entirely in many cases depending on Python version.)

What are Arguments in Python Class Inheritance used for? [duplicate]

This question already has answers here:
What are metaclasses in Python?
(25 answers)
Closed 3 years ago.
When browsing the source code for the django_filters library, I found a class declaration syntax that I've never seen before: inheritance with arguments. I could not find an explanation in the official python class tutorial.
Here is the source, snippet below:
class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass):
pass
what does metaclass=FilterSetMetaclass in the class definition do?
There are two uses for keyword arguments in the list of base classes.
The metaclass argument is used specially to indicate which metaclass (instead of type) to use to create the class. (In Python 2, this was done by assigning a value to the class attribute __metaclass__ in the body of the class statement.)
A class statement is essentially a call to the metaclass.
class Foo(metaclass=Bar):
pass
is equivalent to Foo = Bar('Foo', (), {}). The default metaclass is type, that is
class Foo():
pass
is equivalent to
class Foo(metaclass=type):
pass
Other keyword arguments are passed along to __init_subclass__.
Both of the above are simplifications; see Customizing Class creation for more details.

What is the difference between self and cls argument in classmethod decorator [duplicate]

This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 3 years ago.
class First:
#classmethod
def hello(self):
print(123)
class Second:
#classmethod
def hello(cls):
print(123)
obj1 = First()
obj2 = Second()
print(obj1.hello())
print(obj1.hello())
I am not getting any error while calling obj1 (with self as argument) and obj2 (with cls as argument). Why not? Is the classmethod decorator able to use cls/self?
One will be understood by every reasonably experienced Python programmer.
The other one will confuse every reasonably experienced Python programmer.
The first argument of a classmethod is a class and should be called cls. You can give it any other name in your code, but that's a bad idea, because it still is a class.

Define class functions in different source files? [duplicate]

This question already has answers here:
Define a method outside of class definition?
(5 answers)
Closed 4 years ago.
Is it possible (preserving all the class functionality) to write the class functions in separate files?
Below is an example:
TestClass.py:
class MyClass():
def __init__(self, param1=1, param2=2, param3=3):
self.param1, self.param2, self.param3 =param1, param2, param3,
def ClassFun1(self, param1=2):
return param1**2/self.param2
TestClass2.py:
def ClassFun2(self, param1=3):
return param1*3/self.param2
Next, following this answer, I compile both files (I am too lazy to use import), create a class variable and try to use ClassFun2:
x=MyClass()
x.myMethod=ClassFun2
x.myMethod(2)
As a result, I get an error, since self in ClassFun2 is treated as a parameter, rather than class itself:
AttributeError: 'int' object has no attribute 'param2'
Is it possible to split class definition into several source files? It is possible in C++ and this is actually very convenient when working as a team.
The variable x is an object of the class, not the class itself. You need to do:
x = MyClass
x.myMethod = ClassFun2
Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class.
Then you need to create an instance to execute the method:
y = MyClass()
y.myMethod(2)

Python : Difference between static methods vs class method [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between #staticmethod and #classmethod in Python?
I am learning OOP in python and came to know about these two methods
It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
class Circle:
all_circles = [] # class variable
#staticmethod
def total_area():
for c in Circle.all_circles: # hardcode class name
# do somethig
#classmethod
def total_area(cls):
for c in cls.all_circles: # no hardcode class name
# do something
I see class method as more flexible since we don't hardcode the class
Question:
- Is it even a question which one is better? #staticmethod or #classmethod?
- what are the scenarios suitable to use of each one of these methods?
A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between #staticmethod and #classmethod in Python?

Categories

Resources