What is class structure in Python?
A class in Python is a template that defines the attributes and functions of the objects of that class. The structure of that class is as follows.
classkeyword to declare the class.classNameto name that class, it should be unique.__init__()function to define constructor.methods()functions for the objects.
The basic structure of a class in Python is following:
class className:# Class-level attributesdef __init__(self, parameters):# Constructor methoddef methods(self, parameters):# Method definition
After creating a class, we must access it from the main() function. In order to access the class from main(), we need to create an object of that class. The following code will explain the creation of an object.
class className:# Class-level attributesdef __init__(self, parameters):# Constructor methoddef methods(self, parameters):# Method definitionobject_name = className(arguments)object_name.attribute_nameobject_name.methods(arguments)
Example
The following is an executable example of Python class:
# Create a class "Person"class Person:# function to initialize the name and agedef __init__(self, name, age):self.name = nameself.age = age# class function to determine if a person is adult or notdef adult(self, name, age):if age>=18:print(name, "is an adult.")# crearting a new objectobj = Person("User", 22)# Class constructor and function callprint(obj.name)print(obj.age)obj.adult(obj.name, obj.age)
Explanation
-
Line 2: It creates a
class,Person -
Lines 4–6: It initializes the constructors.
-
Lines 9–11: It determines if the object of that class is an adult or not by comparing the
age. -
Line 14: It creates an object of the
Personclass,obj. -
Lines 16–17: It accesses the functions of the
Personclass. -
Line 18: It calls the
adult()method of the class.
Free Resources