diff --git a/instance-class-static-methods/README.md b/instance-class-static-methods/README.md new file mode 100644 index 0000000000..c106c5cd03 --- /dev/null +++ b/instance-class-static-methods/README.md @@ -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: martin@realpython.com + +## License + +Distributed under the MIT license. See ``LICENSE`` for more information. diff --git a/instance-class-static-methods/demo.py b/instance-class-static-methods/demo.py new file mode 100644 index 0000000000..4ef1fbb7d1 --- /dev/null +++ b/instance-class-static-methods/demo.py @@ -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()) diff --git a/instance-class-static-methods/pizza.py b/instance-class-static-methods/pizza.py new file mode 100644 index 0000000000..9d3243a300 --- /dev/null +++ b/instance-class-static-methods/pizza.py @@ -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, "😋🍕")