-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_method_static_method.py
More file actions
66 lines (47 loc) · 1.55 KB
/
class_method_static_method.py
File metadata and controls
66 lines (47 loc) · 1.55 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
class TestClass:
# instance method has access to the instance of the class.
def instance_method(self):
print(f"calling instance method of {self}")
# class method has access to the class itself.
@classmethod
def class_method(cls):
print(f"calling class method of {cls}")
@staticmethod
def static_method():
print(f"calling a static method.")
# second example
class Book:
TYPE = ("hardcover", "paperback")
def __init__(self, name, book_type, weight):
self.name = name
self.book_type = book_type
self.weight = weight
def __str__(self):
return f"This is {self.name} with {self.book_type} and weights {self.weight}g."
@classmethod
def hardcover(cls, name: str, weight: int) -> "Book":
return cls(name, cls.TYPE[0], weight+100)
@classmethod
def paperback(cls, name:str, weight:int) -> "Book":
return cls(name, cls.TYPE[1], weight)
book = Book.hardcover("harry potter", 150)
light = Book.paperback("hobbit", 140)
#exercises
class Store:
def __init__(self,name):
self.name = name
self.items = []
def add_item(self,name, price):
self.items.append({"name":name, "price":price})
def stock_price(self):
return sum([item["price"] for item in self.items])
@classmethod
def franchise(cls, instance):
return cls(f"{instance.name} - franchise")
@staticmethod
def store_details(store):
return f"{store.name} has a stock price of {store.stock_price()}"
amazon = Store("Amazon")
amazon.add_item("fan", 250)
# print(Store.franchise(amazon).name)
print(Store.store_details(amazon))