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.

  • class keyword to declare the class.
  • className to 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 attributes
def __init__(self, parameters):
# Constructor method
def 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 attributes
def __init__(self, parameters):
# Constructor method
def methods(self, parameters):
# Method definition
object_name = className(arguments)
object_name.attribute_name
object_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 age
def __init__(self, name, age):
self.name = name
self.age = age
# class function to determine if a person is adult or not
def adult(self, name, age):
if age>=18:
print(name, "is an adult.")
# crearting a new object
obj = Person("User", 22)
# Class constructor and function call
print(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 Person class, obj.

  • Lines 16–17: It accesses the functions of the Person class.

  • Line 18: It calls the adult() method of the class.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved