In this Python Classes and Objects article we want to learn about Creating Python Classes and Objects from Scratch, so Python is an object oriented programming language that allows developers to define classes and create objects. in this article we want to explore how to create Python classes and objects from scratch.
Creating Python Classes and Objects from Scratch
So now let’s create our first class in Python, in Python, you can define a class using class keyword, followed by the name of the class. this is an example:
1 2 |
class Employee: pass |
In this example we have define an Employee class that doesn’t do anything. pass statement is a placeholder that allows us to define an empty class.
Now let’s talk about class attributes and methods, classes in Python can have attributes and methods. attributes are like variables that are attached to the class or object, and methods are functions that are attached to the class or object. this is an example of an Employee class with attributes:
1 2 3 4 |
class Employee: def __init__(self, name, age): self.name = name self.age = age |
In this example we have defined an Employee class with two attributes, name and age. after that we have defined a special method called __init__ that is called when a new instance of the class is created. self keyword refers to the instance of the class that is being created. we also set the name and age attributes of the instance using arguments passed to the __init__ method.
1 2 3 4 5 6 7 8 |
class Employee: def __init__(self, name, age): self.name = name self.age = age employee = Employee("GeeksCoders", 5) print("Name is : {}".format(employee.name)) print("Age is : {}".format(employee.age)) |
In this example we have created an Employee object called employee. we pass two arguments to the Employee class. __init__ method is called with these arguments, and name and age attributes of the person object are set.
Run the code and this will be the result
Now let’s talk about Python Class Methods, methods are functions that are attached to a class or an object. you can define methods in a class and call them on an instance of the class. this is an example:
1 2 3 4 5 6 7 8 9 10 |
class Employee: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print(f"Hello my name is {self.name} and I am {self.age} years old") employee = Employee("geekscoders.com", 20) employee.say_hello() |
In this example we have defined say_hello() method in the Employee class. this method takes no arguments and prints a message that includes the name and age attributes of the object. after that we creates a new Employee object called employee and call say_hello() method on it.
This will be the output