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

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?

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.)

Why is the staticmethod decorator necessary? [duplicate]

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

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)

Why its necessary to use any string with dot point with self in class python(self.x=x)? [duplicate]

This question already has answers here:
What do __init__ and self do in Python? [duplicate]
(18 answers)
Closed 6 years ago.
I am learning oop in python so i am having some problem to understand sefl keyword properly.
Suppose a program :
class ge:
def __init__(self,a,b):
self.p=a
self.l=b
def ff(self):
aaa=self.p+self.l
print(aaa)
hh=ge(1,2)
hh.ff()
I am confuse why its necessary to use any string with self with dot ? what it means ? Like:
self.a=a and we can change self.a to ay string like self.b , self.c what it means ?? why its necessary ?
My second question is :
what is difference between defining class with parameter and without parameter ?
class hello(object):
def __init__(self,a,v):
self.a=a
self.v=v
def p(self):
f=self.a+self.v
print(f)
he=hello(1,2)
he.p()
if i defined
class hello(object) its working but
if i defined class like:
class hello(): its also working
but if i defined like:
class hello: its also working
what is the difference class hello(object): , class hello(), class hello:
First question : Duplicate of this question
Second question : There is no difference between the different notations. When you use the parenthesis it means that your class inherits from the class between parenthesis.
In python 3, by default every class inherits from the class object. So hello(object): , class hello():, class hello: are totally equivalent.
In python 2 however, you must explicit the inheritance.
Here are more details on how to create classes in python.
self is used to reference the instance of the class, is like this in Java
Duplicated:
When do you use 'self' in Python?

What does (object) do next to class name in python? [duplicate]

This question already has answers here:
Why do Python classes inherit object?
(6 answers)
Closed 6 years ago.
When you declare a class in python, I often see (object) written next to the class name.
class someClass(object):
def __init__(self, some_variable):
...
...
Is this same as writing below?
class someClass: # didn't write (object) here.
def __init__(self, some_variable):
...
...
I don't really see any difference in terms of how they function. Is it just a way to clarify that someClass is a subclass of object? and is it a good practice to explicitly write object when I make a class?
In Python 2, making someClass a subclass of object turns someClass into a "new-style class," whereas without (object) it's just a "classic class." See the docs or another question here for information on the differences between them; the short answer is that you should always use new-style classes for the benefits they bring.
In Python 3, all classes are "new-style," and writing (object) is redundant.
In python 3.x, they are the same, when you declare:
class C:
def __init__(self):
...
it inherits from object implicitly.
For more information visit this.

Categories

Resources