Created
January 25, 2019 11:43
-
-
Save azm-gh/62a0a22e363c57c4bb4fbab7419221c8 to your computer and use it in GitHub Desktop.
Python's Instance, Class, and Static Methods Demystified
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
class MyClass: | |
def method(self): | |
return 'instance method called', self | |
@classmethod | |
def classmethod(cls): | |
return 'class method called',cls | |
@staticmethod | |
def staticmethod(): | |
return 'static method called' | |
obj = MyClass() | |
print(obj.method()) | |
print(obj.classmethod()) | |
print(obj.staticmethod()) | |
print(MyClass.classmethod()) | |
print(MyClass.staticmethod()) | |
# print(MyClass.method()) | |
#TypeError: method() missing 1 required positional argument: 'self' | |
class Pizza: | |
def __init__(self, ingredients, radius): | |
self.ingredients = ingredients | |
self.radius = radius | |
def __repr__(self): | |
return (f'Pizza({repr(self.radius)}, ' | |
f'{repr(self.ingredients)})') | |
#@property | |
def area(self): | |
return self.circle_area(self.radius) | |
@staticmethod | |
def circle_area(r): | |
return r ** 2 * math.pi | |
@classmethod | |
def margherita(cls): | |
return cls(['mozzarella','tomatoes'] ,2) | |
@classmethod | |
def prosciutto(cls): | |
return cls(['mozarella','tomatoes','ham'], 4) | |
obj = Pizza(['cheese', 'tomatoes'], 5) | |
print(obj) # Pizza(['cheese', 'tomatoes']) | |
print(Pizza.margherita() , Pizza.prosciutto()) | |
p = Pizza(['mozzarella', 'tomatoes'] ,4) | |
print(p.area()) | |
print(Pizza.circle_area(4)) | |
'''One way to look at this use of class methods is that | |
they allow you to define alternative constructors for your classes. | |
They all use the same __init__ constructor internally and simply | |
provide a shortcut for remembering all of the various ingredients.''' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment