How To Create A Simple Class In Python (With Code Example)

 


INTRODUCTION
A class is a plan (Blueprint) or a template  for creating objects. A class defines a set of attributes and methods that objects created from the class will have. A class is define using the class name.

SYNTAX
#creating a class
class ClassName:
    def _ _init_ _(self, parameter_1, parameter_2, ..., parameter_n):
        self.attribute_1=parameter_1
        self.attribute_2=parameter_2
        .
        .
        .
    def methodName(self):
        print("Message")
#Creating an object
object_1=ClassName(arguement_1, arguement_2, ...arguement_n)
#invoke method
object_1.methodName

CODE SAMPLE

class Human:

    def __init__(self, name):

        self.person=name

        self.head=1

        self.eye=2

        self.leg=2

        self.hand=2

        self.mouth=1

        self.nose=1

        self.body=1

    def sing(self):

        print(f"{self.person} have {self.head} head")

        print(f"{self.person} have {self.eye} eyes")

        print(f"{self.person} have {self.mouth} mouth")

        print(f"{self.leg} legs {self.hand} hands")

        print(f"{self.body} body body body {self.nose} nose")

human_object=Human("Joseph")

human_object.sing()

EXPLANATION

Line 1: Create a class Called Human 

Line 2: Create an __init__ constructor Method which is called when the instance of the class Human is created. The  __init__ constructor initialize the value of the object.

Line 3-10: Assign the parameter (name) and value (1 or 2) to the attribute person, eye, head etc.

Line 11: Declare a method called sing that print a Nigerian Pre-nursery song. The sing method define the behaviour of the method. The sing method uses self to refer to the current instance's attributes (like self.head, self.eye, etc.)

Line 17: Creates the object or instance of the class

Line 18: Calls the sing method of the human class.

TRY IT YOURSELF

Write an run the code on your text editor and change some parameter or values, Re run the program to see the result.

CONCLUSION

The tutorial provide a concise guide on how to create class with python. It offers syntax, code example and explanation on the code.


Ameh Joseph Onyeke

Hello and welcome to my blog! My name is Ameh Joseph Onyeke a passionate educator and tech enthusiast with a BSc in Computer Science from Benue State University, a PGDE from the University of Maiduguri, and a Master’s in Software Engineering from Bayero University Kano. My journey blends a strong foundation in computing with a love for teaching, aiming to simplify complex tech concepts for learners at all levels. Through this blog, I provide answers and insights across 10+ programming languages to support students and tech enthusiasts in building their skills and confidence. Whether you're solving coding problems or sharpening your programming abilities, this blog is here to guide you. Let’s learn and grow together!

Post a Comment

Previous Post Next Post