Skip to content

Python objects | Basic

  • by

Python object is created using the class name. 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 variables using object

The variables that belong to a class and are always public, 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 or suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading