Skip to content

Commit 2774a05

Browse files
committed
Add code for methods tutorial
1 parent d2f0c94 commit 2774a05

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Python's Instance, Class, and Static Methods Demystified
2+
3+
This folder contains code related to the tutorial on [Pythons' instance, class, and static methods](https://realpython.com/instance-class-and-static-methods-demystified/).
4+
5+
## About the Author
6+
7+
Martin Breuss - Email: [email protected]
8+
9+
## License
10+
11+
Distributed under the MIT license. See ``LICENSE`` for more information.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class DemoClass:
2+
def instance_method(self):
3+
return ("instance method called", self)
4+
5+
@classmethod
6+
def class_method(cls):
7+
return ("class method called", cls)
8+
9+
@staticmethod
10+
def static_method():
11+
return ("static method called",)
12+
13+
14+
if __name__ == "__main__":
15+
obj = DemoClass()
16+
print(obj.instance_method())
17+
print(obj.class_method())
18+
print(obj.static_method())
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Pizza:
2+
def __init__(self, toppings):
3+
self.toppings = list(toppings)
4+
5+
def __repr__(self):
6+
return f"Pizza({self.toppings})"
7+
8+
def add_topping(self, topping):
9+
self.toppings.append(topping)
10+
11+
def remove_topping(self, topping):
12+
if topping in self.toppings:
13+
self.toppings.remove(topping)
14+
15+
@classmethod
16+
def margherita(cls):
17+
return cls(["mozzarella", "tomatoes"])
18+
19+
@classmethod
20+
def prosciutto(cls):
21+
return cls(["mozzarella", "tomatoes", "ham"])
22+
23+
@staticmethod
24+
def get_size_in_inches(size):
25+
"""Returns an approximate diameter in inches for common sizes."""
26+
size_map = {"small": 8, "medium": 12, "large": 16}
27+
return size_map.get(size, "Unknown size")
28+
29+
30+
if __name__ == "__main__":
31+
a_pizza = Pizza.margherita()
32+
print(a_pizza, "😋🍕")

0 commit comments

Comments
 (0)