Skip to content

Instantly share code, notes, and snippets.

@azm-gh
Created January 25, 2019 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azm-gh/62a0a22e363c57c4bb4fbab7419221c8 to your computer and use it in GitHub Desktop.
Save azm-gh/62a0a22e363c57c4bb4fbab7419221c8 to your computer and use it in GitHub Desktop.
Python's Instance, Class, and Static Methods Demystified
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