forked from tecladocode/python-refresher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
51 lines (35 loc) · 1.37 KB
/
code.py
File metadata and controls
51 lines (35 loc) · 1.37 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
class ClassTest:
def instance_method(self):
print(f"Called instance_method of {self}")
@classmethod
def class_method(cls):
print(f"Called class_method of {cls}")
@staticmethod
def static_method():
print(f"Called static_method. We don't get any object or class info here.")
instance = ClassTest()
instance.instance_method()
ClassTest.class_method()
ClassTest.static_method()
# -- What are they used for? --
# Instance methods are used for most things. When you want to produce an action that uses the data stored in an object.
# Static methods are used to just place a method inside a class because you feel it belongs there (i.e. for code organisation, mostly!)
# Class methods are often used as factories.
class Book:
TYPES = ("hardcover", "paperback")
def __init__(self, name, book_type, weight):
self.name = name
self.book_type = book_type
self.weight = weight
def __repr__(self):
return f"<Book {self.name}, {self.book_type}, weighing {self.weight}g>"
@classmethod
def hardcover(cls, name, page_weight):
return cls(name, cls.TYPES[0], page_weight + 100)
@classmethod
def paperback(cls, name, page_weight):
return cls(name, cls.TYPES[1], page_weight)
heavy = Book.hardcover("Harry Potter", 1500)
light = Book.paperback("Python 101", 600)
print(heavy)
print(light)