Skip to content

Instantly share code, notes, and snippets.

@always-hii
Created May 16, 2018 02:19
Show Gist options
  • Save always-hii/873eab4f844484b2cc654840b4ca066b to your computer and use it in GitHub Desktop.
Save always-hii/873eab4f844484b2cc654840b4ca066b to your computer and use it in GitHub Desktop.
Example of class method and static method in Python
class iPhone:
iphone_list = ["3g", "3gs", "4", "4S", "5", "5s"]
def __init__(self, model):
self.model = model
@classmethod
def from_year(cls, year):
return cls(iPhone.iphone_list[int(year) - 2008])
@staticmethod
def what_is_newest():
return iPhone.iphone_list[len(iPhone.iphone_list) - 1]
def __repr__(self):
return self.model
a = iPhone("3g")
b = iPhone.from_year(2008)
print("Newest Model: "+iPhone.what_is_newest())
print("a has "+str(a))
print("b has "+str(b))
print("a==b: " + str(a == b))
print("a.model==b.model: " + str(a.model == b.model))
# Newest Model: 5s
# a has 3g
# b has 3g
# a==b: False
# a.model==b.model: True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment