Python Classes
Python Classes
Python Classes
Objects:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Example:
class Person:
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
Example:
class Person:
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
p1.myfunc()
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:
Example:
class Person:
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
p1.myfunc()
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
del p1.age
print(p1.age)
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Example:
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
super() Function
Python also has a super() function that will make the child class inherit all the methods and
properties from its
Example:
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()