Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Last active August 30, 2017 22:05
Show Gist options
  • Select an option

  • Save rcanepa/6ce22eb9e878335da6038a8612e06562 to your computer and use it in GitHub Desktop.

Select an option

Save rcanepa/6ce22eb9e878335da6038a8612e06562 to your computer and use it in GitHub Desktop.
Classes, Methods, Class and Instance Variables, Inheritance in Python 3
class Shark:
shark_type = "White Shark" # class variable
def __init__(self, name):
print("I am being constructed!")
self.name = name # instance variable
def swim(self):
print("The shark is swimming.")
def be_awesome(self):
print("{} the shark is being awesome.".format(self.name))
bob = Shark("Bob")
=> "I am being constructed!"
bob.shark_type
=> "White Shark"
bob.be_awesome()
=> "Bob the shark is being awesome."
# We use the "class" statement to create a class
class Human:
# A class attribute. It is shared by all instances of this class
species = "H. sapiens"
# Basic initializer, this is called when this class is instantiated.
# Note that the double leading and trailing underscores denote objects
# or attributes that are used by Python but that live in user-controlled
# namespaces. Methods(or objects or attributes) like: __init__, __str__,
# __repr__ etc. are called special methods (or sometimes called dunder methods)
# You should not invent such names on your own.
def __init__(self, name):
# Assign the argument to the instance's name attribute
self.name = name
# Initialize property
self._age = 0
# An instance method. All methods take "self" as the first argument
def say(self, msg):
print ("{name}: {message}".format(name=self.name, message=msg))
# Another instance method
def sing(self):
return 'yo... yo... microphone check... one two... one two...'
# A class method is shared among all instances
# They are called with the calling class as the first argument
@classmethod
def get_species(cls):
return cls.species
# A static method is called without a class or instance reference
@staticmethod
def grunt():
return "*grunt*"
# A property is just like a getter.
# It turns the method age() into an read-only attribute of the same name.
# There's no need to write trivial getters and setters in Python, though.
@property
def age(self):
return self._age
# This allows the property to be set
@age.setter
def age(self, age):
self._age = age
# This allows the property to be deleted
@age.deleter
def age(self):
del self._age
class Duck:
def quack(self):
print("Quack, quack!")
def fly(self):
print("Flap, Flap!")
class Person:
def quack(self):
print("I'm Quackin'!")
def fly(self):
print("I'm Flyin'!")
def in_the_forest(mallard):
mallard.quack()
mallard.fly()
in_the_forest(Duck())
=> "Quack, quack!"
=> "Flap, Flap!"
in_the_forest(Person())
=> "I'm Quackin'!"
=> "I'm Flyin'!"
class Fish: # parent class
def __init__(self, first_name, last_name="Fish",
skeleton="bone", eyelids=False):
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def swim(self):
print("The fish is swimming.")
def swim_backwards(self):
print("The fish can swim backwards.")
class Trout(Fish): # child class
pass
terry = Trout("Terry")
terry.first_name + " " + terry.last_name
=> "Terry Fish"
terry.skeleton
=> "bone"
terry.eyelids
=> False
terry.swim()
=> "The fish is swimming."
terry.swim_backwards()
=> "The fish can swim backwards."
class Clownfish(Fish): # another child class
def live_with_anemone(self):
print("The clownfish is coexisting with sea anemone.")
casey = Clownfish("Casey")
casey.first_name + " " + casey.last_name
=> "Casey Fish"
casey.swim()
=> "The fish is swimming."
casey.live_with_anemone()
=> "The clownfish is coexisting with sea anemone."
terry.live_with_anemone()
=> AttributeError: 'Trout' object has no attribute 'live_with_anemone'
class Shark(Fish): # another child class
def __init__(self, first_name, last_name="Shark",
skeleton="cartilage", eyelids=True): # overrides skeleton & eyelids
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def swim_backwards(self): # overrides this method as well
print("The shark cannot swim backwards, but can sink backwards.")
sammy = Shark("Sammy")
sammy.first_name + " " + sammy.last_name
=> "Sammy Shark"
sammy.swim()
=> "The fish is swimming."
sammy.swim_backwards()
=> "The shark cannot swim backwards, but can sink backwards."
sammy.eyelids
=> True
sammy.skeleton
=> "cartilage"
# Using super() to access overwritten methods from the parent class
class Salmon(Fish): # child class
def __init__(self, water = "freshwater"):
self.water = water
super().__init__(self) # calling the parent class constructor
gus = Salmon()
# Initialize first name
gus.first_name = "Gus"
# Use parent __init__() through super()
gus.first_name + " " + gus.last_name
=> "Gus Fish"
gus.eyelids
=> False
# Use child __init__() override
gus.water
=> "freshwater"
# Use parent swim() method
gus.swim()
=> "The fish is swimming."
class A:
def m1(self):
return “I am A”
class B:
def m1(self):
return “I am BA”
def m2(self):
return “I am B”
class C(A,B):
def m3(self):
return “I am C”
c = C()
print(c.m1())
# Since C does not implement m1, it will take the first superclass
# from the left(A). Since m1 is implemented in A, it will call A.m1()
# and print its result: “I am A”.
print(c.m2())
# C does not implement m2. C will look m2 in A (first from the left).
# Finally, C will find m2 in B, which will print its result: “I am B”.
class AudioFile:
def __init__(self, filename):
if not filename.endswith(self.ext):
raise Exception("Invalid file format")
self.filename = filename
class MP3File(AudioFile):
ext = "mp3"
def play(self):
print("playing {} as mp3".format(self.filename))
class WavFile(AudioFile):
ext = "wav"
def play(self):
print("playing {} as wav".format(self.filename))
music = MP3File("myfile.mp3")
music.play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment