Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions instance-class-static-methods/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Python's Instance, Class, and Static Methods Demystified

This folder contains code related to the tutorial on [Pythons' instance, class, and static methods](https://realpython.com/instance-class-and-static-methods-demystified/).

## About the Author

Martin Breuss - Email: [email protected]

## License

Distributed under the MIT license. See ``LICENSE`` for more information.
18 changes: 18 additions & 0 deletions instance-class-static-methods/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class DemoClass:
def instance_method(self):
return ("instance method called", self)

@classmethod
def class_method(cls):
return ("class method called", cls)

@staticmethod
def static_method():
return ("static method called",)


if __name__ == "__main__":
obj = DemoClass()
print(obj.instance_method())
print(obj.class_method())
print(obj.static_method())
32 changes: 32 additions & 0 deletions instance-class-static-methods/pizza.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Pizza:
def __init__(self, toppings):
self.toppings = list(toppings)

def __repr__(self):
return f"Pizza({self.toppings})"

def add_topping(self, topping):
self.toppings.append(topping)

def remove_topping(self, topping):
if topping in self.toppings:
self.toppings.remove(topping)

@classmethod
def margherita(cls):
return cls(["mozzarella", "tomatoes"])

@classmethod
def prosciutto(cls):
return cls(["mozzarella", "tomatoes", "ham"])

@staticmethod
def get_size_in_inches(size):
"""Returns an approximate diameter in inches for common sizes."""
size_map = {"small": 8, "medium": 12, "large": 16}
return size_map.get(size, "Unknown size")


if __name__ == "__main__":
a_pizza = Pizza.margherita()
print(a_pizza, "😋🍕")