-
Notifications
You must be signed in to change notification settings - Fork 0
/
classmethod.py
58 lines (44 loc) · 1.17 KB
/
classmethod.py
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
from datetime import date
class Fruit:
name = 'Fruits'
@classmethod
def printName(cls):
print('The name is:', cls.name)
# Alternative writing
class AltFruit:
name = 'Fruits'
def printName(cls):
print('The name is:', cls.name)
# 2 Example
class Person:
CONFIG = {
'foo': 42
}
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def details(cls, name, year):
return cls(name, date.today().year - year)
@classmethod
def foo(cls):
print(cls.CONFIG)
@staticmethod
def check_age(age):
print(age > 18)
if __name__ == "__main__":
apple = Fruit()
berry = Fruit()
Fruit.printName()
apple.printName()
berry.printName()
print('\nAlternative writing:')
AltFruit.printAge = classmethod(AltFruit.printName) # use classmethod here
AltFruit.printAge()
print('\n2 Example:')
person1 = Person('Mark', 20)
person2 = Person.details('Rohan', 1992)
print(person1.name, person1.age)
print(person2.name, person2.age)
Person.check_age(25)
Person.foo()