-
Notifications
You must be signed in to change notification settings - Fork 0
/
classes_staticandclassmethods.py
105 lines (77 loc) · 2.44 KB
/
classes_staticandclassmethods.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# -*- coding: utf-8 -*-
"""
Simply study related to static and class methods
"""
import datetime
# First Example
class Warrior(object):
# delta position - class variable
delta_position = 10
#number of warriors
num_of_warriors = 0
def __init__(self,posx,posy):
self.posx = posx
self.posy = posy
Warrior.num_of_warriors+=1
def move(self, posx,posy):
self.posx = posx+ self.delta_position
self.posy = posy +self.delta_position
def position(self):
return '{} , {}' .format(self.posx, self.posy)
# Second Example
class Monster(object):
# delta position - class variable
delta_position = 10
#number of monters
num_of_monsters = 0
def __init__(self, posx, posy):
self.posx = posx
self.posy = posy
Monster.num_of_monsters+= 1
def move(self, posx,posy):
self.posx = posx + self.delta_position
self.posy = posy + self.delta_position
def position(self):
return '{} , {}' .format(self.posx,self.posy)
# used to change the value of class variable
# same as Monster.delta_position = new_value
@classmethod
def set_move(cls,inc):
cls.delta_position = inc
#using classmethod as alternatives consctructor
@classmethod
def from_str(cls, pos_str):
posx, posy = pos_str.split("-")
return cls(posx, posy)
#static methods
#behaves like a regular function
@staticmethod
def is_gameday(day):
if day.weekday == 5 or day.weekday == 6:
return False
return True
if __name__ == "__main__":
# First Example
# declare an instance of Warrior Class
Savage = Warrior(20, 10)
Savage.move(10, 25)
print(Savage.position())
# print namespace of instance
print(Savage.__dict__)
# print namespace of class Warrior
print(Warrior.__dict__)
# print number of objects
print(Warrior.num_of_warriors)
# Second Example
monster = Monster(30, 20)
print(monster.position())
# change value of class variable
Monster.set_move(5)
monster.move(10, 10)
print(monster.position())
# using the "alternative constructor"
second_monster = Monster.from_str("10-30")
print(second_monster.__dict__)
# to test staticmethod
now = datetime.datetime.now()
print(Monster.is_gameday(now))