-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclass_vs_static_method.py
More file actions
71 lines (52 loc) · 1.93 KB
/
class_vs_static_method.py
File metadata and controls
71 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Class Method:
A class method receives the class as an implicit first argument, just like an instance method receives the instance.
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
- They have the access to the state of the class as it takes a class parameter that points to the class
and not the object instance.
- It can modify a class state that would apply across all the instances of the class.
- We generally use class method to create factory methods. Factory methods return class objects
( similar to a constructor ) for different use cases.
Static Method:
A static method does not receive an implicit first argument.
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
- A static method can’t access or modify the class state.
- A static method is also a method that is bound to the class and not the object of the class.
- We generally use static methods to create utility functions.
"""
from datetime import date
class Person:
_entity = "Person"
def __init__(self, name, age):
self._name = name
self._age = age
@classmethod
def from_birth_year(cls, name, year):
# modifying class state that would apply across all instances of the class
cls._entity = "Student"
return cls(name, date.today().year - year)
@staticmethod
def is_adult(age):
# static methods are usually utility functions
return age > 18
person1 = Person("mayank", 21)
print(person1._entity)
person2 = Person.from_birth_year("mayank", 1996)
print(person2._entity)
# Modify class variable
# Person._entity = "Student"
print(person1._entity)
print(person1._age)
print(person2._age)
print(Person.is_adult(22))
print(" ----------------------------------- ")
print("creating different instance")
person3 = Person("Ayush", 27)
print(person3._entity)
print(person3._age)