Python Classes and Objects

Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a “blueprint” for creating objects.

1. CREATE A CLASS IN PYTHON

To create a class, use the keyword class

# Create a class name called “MyClass”
class MyClass:
    x = 5

OUTPUT:

CREATE CLASS IN PYTHON
OUTPUT – CREATE CLASS IN PYTHON

2. CREATE A OBJECT OF CLASS IN PYTHON

# Create a class name called “MyClass”
class MyClass:
    x = 5

# Now we use class name "myClass" to create object
# Create an object named p1 & then print the value of x
p1 = MyClass()
print(p1.x)

OUTPUT:

CREATE OBJECT OF CLASS IN PYTHON
OUTPUT – CREATE OBJECT OF CLASS IN PYTHON

3. THE __INIT__() FUNCTION IN PYTHON

The examples above are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes we have to understand the built-in __init__() function. All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.

For example:

# Create a class named "Person"
class Person:
    # use the __init__() function to assign values for name & age
    def __init__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("John", 36)
print(p1.name)
print(p1.age)

OUTPUT:

INIT METHOD (FUNCTION) IN PYTHON
OUTPUT – INIT METHOD (FUNCTION) IN PYTHON

4. ACCESS CLASS METHODS IN PYTHON

Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def myfunc(self):
        print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

OUTPUT:

CLASS METHOD IN PYTHON
OUTPUT – CLASS METHOD IN PYTHON

Leave a Reply

Your email address will not be published. Required fields are marked *