26
loading...
This website collects cookies to deliver better user experience
class ClassName:
<statement-1>
<statement-N>
class Student:
"""A simple example class"""
rollno = 12
name = "Korir"
def messg(self):
return 'New Session will start soon.'
From the above example, Student.roll_no, Student.name are valid attribute references, returning an 12 and 'Korir' respectively.
Student.messg returns a function object.
In Python self is a name for the first argument of a method which is different from ordinary function. Rather than passing the object as a parameter in a method the word self refers to the object itself.
x = Student()
def __init__(self):
self.data = []
class Student:
"""A simple example class"""
def __init__(self,sroll, sname):
self.r = sroll
self.n = sname
x = Student(10, 'Korir')
x.r, x.n
(10, 'Korir')
x.messg()
class Circle:
def __ init __(self, radius):
self.pi = 3.14159
self.radius = radius
def area(self):
return self.pi * self.radius**2
def circumference(self):
return 2*self.pi * self.radius
class Circle:
pi = 3.14159
def __init__(self, radius):
self.radius = radius
def area(self):
return self.pi * self.radius**2
def circumference(self):
return 2 * self.pi * self.radius
object_name.class_attribute
class_name.class_attribute
c = Circle(10)
print(c.pi)
print(Circle.pi)
3.14159
3.14159
class DerivedClassName(BaseClassName):
<statement-1>
<statement-N>
class Parent():
def first(self):
print('first function')
class Child(Parent):
def second(self):
print('second function')
ob = Child()
ob.first()
ob.second()
first function
second function
Calling a constructor of the parent class by mentioning the parent class name in the declaration of the child class is known as sub-classing. A child class identifies its parent class by sub-classing.
Other types of inheritance are;