0
what is the difference between classmethod amd static method?
5 Réponses
+ 11
Class methods are passed the calling class, static methods aren't
+ 8
instance method -> implicit first argument is an instance of the class
class method -> implicit first argument is the class
static method -> no implicit first arguments
class Cls:
def instance_meth(self, a):
print(self, a)
@classmethod
def class_meth(cls, a):
print(cls, a)
@staticmethod
def static_meth(a):
print(a)
c = Cls()
c.instance_meth(1)
#Cls.instance_meth(1) #TypeError
c.class_meth(2)
Cls.class_meth(3)
c.static_meth(4)
Cls.static_meth(5)
+ 4
Basically, there are instance methods, class methods and static methods.
An instance method is always linked to a specific instance of a class. The instance is usually referenced with the variable "self". In a Person class, an instance method "get_age" could look like this:
class Person(object):
def __init__(self, name, age):
self._name = name
self._age = age
def get_age(self): # instance method
return self._age
You can create a new Person instance like this:
p1 = Person('John', 85)
and get its age like this:
print(p1.get_name()) # 85
A class method is linked to the class itself and returns an instance of the class. It usually takes "cls" as a reference to the class.
Let's say you want to create a new Person instance from a string like "Hubert, 123". Your class method could look like this:
@classmethod
def from_string(cls, string):
name, age = string.split(',')
age = int(age)
return cls(name, age)
You can call the class method like this:
p2 = Person.from_string('Hubert, 123')
The class method will take the string "Hubert, 123", split it into "Hubert" and 123 and return a new Person instance with these parameters.
A static method is linked neither to a specific instance of the class nor to the class itself, hence it doesn't take any parameters like "self" or "cls".
An instance method that checks if a string contains a valid name and age for a Person instance could look like this:
@staticmethod
def check_valid_string(string):
import re
name_pattern = re.compile(r'^([A-Z][a-z]+),\s*(\d+)#x27;)
m = name_pattern.match(string)
if m:
name, age = m.groups()
age = int(age)
if not 0 <= age <= 120:
return False
else:
return False
return True
You can call the static method like this:
print(Person.check_valid_string('Peter, 45')) # True
print(Person.check_valid_string('Doris, 546')) # False
+ 1
class method are calling the class ........................................ select this option
- 2
Question : What is the difference between a class method and a static method?
answer : Class methods are inherited, static methods aren't