Python objects | Basic

Python object is created using the class name. A python is an object-oriented programming language. Where objects are simply a collection of attributes (variables) and functions.

Syntax

<object-name> = <class-name>(<arguments>)   

Python objects examples

Simple example code created the object of MyClass class.

class MyClass:
    var = 10


# Creating object
obj = MyClass()

print(obj)
print(type(obj))

Output:

Python objects

Accessing variable using object

The variables that belong to a class and are always public, it can be accessed using the dot (.) operator.

class MyClass:
    var = 10


test = MyClass()

print(test.var)

Output: 10

Python object access method

This example created an Employee class that consisted of two attributes name, salary, and display function. We created the object of the Employee class called emp1. Using the object along with the .dot operator, we accessed the class function.

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

    def my_func(self):
        print("Name " + self.name)


emp1 = Employee("John", 36000)
emp1.my_func()

Output: Name John

Do comment if you have any doubts and suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.