Class
Python Class
Section titled “Python Class”Python is a completely object-oriented language. You have been working with classes and objects right from the beginning of these tutorials. Every element in a Python program is an object of a class. A number, string, list, dictionary, etc., used in a program is an object of a corresponding built-in class. You can retrieve the class name of variables or objects using the type() method, as shown below. type()
num=20print(type(num)) #<class 'int'>
s="Python"print(type(s)) #<class 'str'>`num=20 print(type(num)) #<class ‘int’>
s=“Python” print(type(s)) #<class ‘str’>`Try it
Defining a Class
Section titled “Defining a Class”A class in Python can be defined using the class keyword.
class
class <ClassName>: <statement1> <statement2> . . <statementN>class <ClassName>: <statement1> <statement2> . . <statementN>
As per the syntax above, a class is defined using the class keyword followed by the class name and : operator after the class name, which allows you to continue in the next indented line to define class members. The followings are class members.
class``:1. Class Attributes
Class Attributes1. Constructor
Constructor1. Instance Attributes
Instance Attributes1. Properties
Properties1. Class Methods
Class Methods
A class can also be defined without any members. The following example defines an empty class using the pass keyword.
pass
class Student: passclass Student: pass
Class instantiation uses function notation. To create an object of the class, just call a class like a parameterless function that returns a new object of the class, as shown below.
std = Student()std = Student()
Above, Student() returns an object of the Student class, which is assigned to a local variable std. The Student class is an empty class because it does not contain any members.
Student()``Studentvariablestd``Student
Class Attributes
Section titled “Class Attributes”Class attributes are the variables defined directly in the class that are shared by all objects of the class. Class attributes can be accessed using the class name as well as using the objects.
class Student: schoolName = 'XYZ School'class Student: schoolName = 'XYZ School'
Above, the schoolName is a class attribute defined inside a class. The value of the schoolName will remain the same for all the objects unless modified explicitly.
schoolName``schoolName
print(Student.schoolName) #'XYZ School'
Student.schoolName = 'ABC School'print(Student.schoolName) #'ABC School'
std = Student()print(std.schoolName) #'ABC School'
std.schoolName = 'Super School'print(std.schoolName) #'Super School'
print(Student.schoolName) #'ABC School'`print(Student.schoolName) #‘XYZ School’
Student.schoolName = ‘ABC School’ print(Student.schoolName) #‘ABC School’
std = Student() print(std.schoolName) #‘ABC School’
std.schoolName = ‘Super School’ print(std.schoolName) #‘Super School’
print(Student.schoolName) #‘ABC School’[Try it](/codeeditor?cid=python-3z8rqvw3n) As you can see, a class attribute is accessed by Student.schoolName as well as std.schoolName. Changing the value of class attribute using the class name would change it across all instances. However, changing class attribute value using instance does not reflect to other instances or class. Student.schoolName“std.schoolNameThe following example demonstrates the use of class attribute count.count`
class Student: count = 0 def __init__(self): Student.count += 1class Student: count = 0 def __init__(self): Student.count += 1
In the above example, count is an attribute in the Student class. Whenever a new object is created, the value of count is incremented by 1. You can now access the count attribute after creating the objects, as shown below.
count``count``count
std1=Student()print(Student.count) #1
std2 = Student()print(Student.count) #2
std3 = Student()print(Student.count) #3`std1=Student() print(Student.count) #1
std2 = Student() print(Student.count) #2
std3 = Student() print(Student.count) #3`Try it
Constructor
Section titled “Constructor”In Python, the constructor method is invoked automatically whenever a new object of a class is instantiated, same as constructors in C# or Java. The constructor must have a special name init() and a special parameter called self.
__init__()``self
The first parameter of each method in a class must be the self , which refers to the calling object. However, you can give any name to the first parameter, not necessarily self.
self ``self
The following example defines a constructor.
class Student: def __init__(self): # constructor method print('Constructor invoked')
s1 = Student()s2 = Student()`class Student: def init(self): # constructor method print(‘Constructor invoked’)
s1 = Student()
s2 = Student()[Try it](/codeeditor?cid=python-3z8rrntsy) In the above example, whenever you create an object of the Student class, the __init__() constructor method will be called. Student“init()`
In Python, the constructors are mostly used to define instance attributes and assign their default values.
Instance Attributes
Section titled “Instance Attributes”Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.
The following example defines instance attributes name and age in the constructor.
name``age
class Student: schoolName = 'XYZ School' # class attribute
def __init__(self): # constructor self.name = '' # instance attribute self.age = 0 # instance attribute`class Student: schoolName = ‘XYZ School’ # class attribute
def __init__(self): # constructor self.name = '' # instance attribute self.age = 0 # instance attribute`You can get or set the value of instance attributes using the dot notation: [instance name].[attribute name], as shown below.
[instance name].[attribute name]
std = Student()print(std.name) #''print(std.age) #0
std.name = "Bill"std.age=25print(std.name) #'Bill'print(std.age) #25`std = Student() print(std.name) #” print(std.age) #0
std.name = “Bill”
std.age=25
print(std.name) #‘Bill’
print(std.age) #25[Try it](/codeeditor?cid=python-3z8rrwf7p) You can specify the values of instance attributes through the constructor. The following constructor includes the name and age parameters, other than the self parameter. self`
class Student: def __init__(self, name, age): self.name = name self.age = age
std = Student('Bill',25) #passing values to constructorprint(std.name)print(std.age)`class Student: def init(self, name, age): self.name = name self.age = age
std = Student(‘Bill’,25) #passing values to constructor print(std.name) print(std.age)`Try it As you can see, you can pass the attributes value while creating an instance.
You don’t have to specify the value of the self parameter. It will be assigned internally in Python.
self
You can also set default values to the instance attributes. The following code sets the default values of the constructor parameters. So, if the values are not provided when creating an object, the values will be assigned latter.
class Student: def __init__(self, name="Guest", age=25) self.name=name self.age=age
std = Student()print(std.name) #'Guest'print(std.age) #25`class Student: def init(self, name=“Guest”, age=25) self.name=name self.age=age
std = Student() print(std.name) #‘Guest’ print(std.age) #25`Try it Visit class attributes vs instance attributes in Python for more information. class attributes vs instance attributes in Python
Class Properties
Section titled “Class Properties”In Python, a property in the class can be defined using the property() function.
property() function
The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#.
property()
The property() method takes the get, set and delete methods as arguments and returns an object of the property class.
property()``property
The following example demonstrates how to create a property in Python using the property() function.
property()
class Student: def displayInfo(self): # class method print('Student Information')
#create objectstd = Student()std.displayInfo() #calling method`class Student: def displayInfo(self): # class method print(‘Student Information’)
#create object
std = Student()
std.displayInfo() #calling method[Try it](/codeeditor?cid=python-3z8uabqgd) In the above displayInfo() method, self is just a conventional name for the first argument. The method can be called as object.method(). displayInfo()selfobject.method()The first parameter of the method need not be named self. You can give any name that refers to the instance of the calling method. The following displayInfo() method names the first parameter as obj instead of self and that works perfectly fine.selfdisplayInfo()obj“self`
class Student: def displayInfo(obj): # class method print('Student Information')class Student: def displayInfo(obj): # class method print('Student Information')
Defining a method in the class without the self parameter would raise an exception when calling a method.
self
class Student: def displayInfo(): # method without self parameter print('Student Information')
std = Student()std.displayInfo() #error`class Student: def displayInfo(): # method without self parameter print(‘Student Information’)
std = Student()
std.displayInfo() #errorThe method can access instance attributes using the self parameter.self`
class Student: def __init__(self, name, age): self.name = name self.age = age def displayInfo(self): # class method print('Student Name: ', self.name,', Age: ', self.age)class Student: def __init__(self, name, age): self.name = name self.age = age def displayInfo(self): # class method print('Student Name: ', self.name,', Age: ', self.age)
You can now invoke the method, as shown below.
std = Student('Steve', 25)std.displayInfo()std = Student('Steve', 25) std.displayInfo()Try it
Deleting Attribute, Object, Class
Section titled “Deleting Attribute, Object, Class”You can delete attributes, objects, or the class itself, using the del keyword, as shown below.
del
class Student: def __init__(self, name, age): self.name = name self.age = age def displayInfo(self): # class method print('Student Name: ', self.name,', Age: ', self.age)
std = Student('Steve', 25)std.displayInfo()
del std.name # deleting attributeprint(std.name) #error
del stdprint(std.name) #error
del Student # deleting classstd = Student('Steve', 25) #error`class Student: def init(self, name, age): self.name = name self.age = age def displayInfo(self): # class method print(‘Student Name: ’, self.name,’, Age: ’, self.age)
std = Student(‘Steve’, 25) std.displayInfo()
del std.name # deleting attribute print(std.name) #error
del std print(std.name) #error
del Student # deleting class std = Student(‘Steve’, 25) #error`Try it