classAnimal:pass
x = Animal()print(type(x))# <class '__main__.Animal'>
Methods
classCircle:
pi =3.14# Circle gets instantiated with a radius (default is 1)def__init__(self, radius=1):
self.radius = radius
self.area = radius * radius * Circle.pi
# Method for resetting RadiusdefsetRadius(self, new_radius):
self.radius = new_radius
self.area = new_radius * new_radius * self.pi
# Method for getting CircumferencedefgetCircumference(self):return self.radius * self.pi *2
c = Circle()print('Radius is: ',c.radius)print('Area is: ',c.area)print('Circumference is: ',c.getCircumference())# Radius is: 1# Area is: 3.14# Circumference is: 6.28
Inheritance
classAnimal:def__init__(self):print("Animal created")defwhoAmI(self):print("Animal")defeat(self):print("Eating")classDog(Animal):def__init__(self):
Animal.__init__(self)print("Dog created")defwhoAmI(self):print("Dog")defbark(self):print("Woof!")
d = Dog()# Animal created# Dog created
d.whoAmI()# Dog
d.eat()# Eating
d.bark()# Woof!
Polymorphism
classDog:def__init__(self, name):
self.name = name
defspeak(self):return self.name+' says Woof!'classCat:def__init__(self, name):
self.name = name
defspeak(self):return self.name+' says Meow!'
niko = Dog('Niko')
felix = Cat('Felix')print(niko.speak())print(felix.speak())# Niko says Woof!# Felix says Meow!
Special Methods
classMovie:def__init__(self, title, director, length):print("A movie is created")
self.title = title
self.director = director
self.length = length
def__str__(self):return"Title: %s, director: %s, Time(mins): %s"%(self.title, self.director, self.length)def__len__(self):return self.length
def__del__(self):print("A movie is destroyed")
movie = Movie("Matrix","Wachowski",150)#Special Methodsprint(movie)print(len(movie))del movie
A personal blog by Volkan Uyarer. Developer, Lifelong Learner, Tech Enthusiast.