Python Classes and Objects Example

Sovary June 24, 2022 345
5 minutes read

Hello friends, today we are going to learn about what is class and object in Python. We will go through step by step with simple explain for beginner to catch up easily. We will give use-case example, so that you will good to go in future programming tutorial.

python class object example

Class and Object are like you and your shadow. A Class is you and you can create shadow which is an Object. Your will learn both of them but first we will go to what is class in Python first?

Also read: Python - Show Date Time in Different Format

1. What is Class in Programming?

Class in term programming is a blueprint or prototype which hold attributes, functionality what the Class can do. I will give an example to more understand. In real world, a car have their own information such as model, color, manufacturing year, max speed.

If we build a system to manage car information, we will defined car as a Class; each Class have their own fields which are model, color, manufacturing year, max speed, and a Class can perform action such as self-drive, drive on water, drive off road... remember one thing is field (property) is always part-of speech in noun, and function (method) is part-of speech in verb.

1.1. Create a Class

In Python we use class keyword to define a Class

Example #1 - Create Simple Class

class Person:
  name = "sovary"

We created a class named Person, with a field named name. We can add more property and functionality what class can do.

Example #2 - Create Class Without any Attribute

class Person:
  pass

In some case, we want to create Class but nothing implement inside, we have to put keyword pass so that compiler will not produce error.

Example #3 - Class with Attributes

class Person:
  name = "sovary"
  age = 22

  def Walk():
    return "I am walk now"

We have added new function which is Walk(), so walk is action what class can do. Now we are going to explain special function which is a built-in function that is hidden in a Class.

All Class in Python contain a function called __init__() which is automatically executed when the Class is being initiated. In programming is called constructor. This function is usually use to assign value to Class property when Object is created.

Example #4 - Class with Constructor

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

  def TellYourSelf(self):
    return f"My name is {self.name} age: {self.age}"

We will see further example use-case to activate this Class in Object section.

2. What is Object in Programming?

If you understand about Class, it more easily to understand about Object. Object is a result from Class which was instantiated. In real application we use Object to create different instance by blueprint of Class.

2.1 Create an Object

There is no keyword to define an Object because it comes from the Class which we have implemented.

Example #1 - Instance Object with Simple Class

# Defined a class
class Person:
  name = "sovary"

# Creating object from class Person
p = Person()
# Accessing property class and print
print(p.name)

Output #1

sovary

We have a Class named "Person" which have property named "name" and assigned default value. To instance an Object we have to call Class name with parenthesis. By accessing any attributes we are using the object name prefix with dot operator.

Example #2 - Create Object with Initiate Data

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

  def TellYourSelf(self):
    return f"My name is {self.name} age: {self.age}"

# Instance object with initiate value
p = Person("Hong",44)
print(p.TellYourSelf())

Output #2

My name is Hong age: 44

We know special function (constructor) is always hidden. After we defined, the constructor turn to visible and required two parameters name, and age but wait... I saw three parameters include self parameter.

The self parameter is a refer to the current object of the Class. We set self keyword at first place parameter so that the constructors or functions can access the variables which belong to that Class.

In the example above we have self keyword because we want to assign the value from instance the Object to property Class.

2.2 Set or Modify Object Property

Intentionally to create Class and Object is to set the property to different value. Example again, a car have different attributes: brand, model, speed, color and can run off road, drive on water etc. We create Object from Class Car and set different properties value base on what we want produce or set.

Example #1 - Modify Default Value with Different Object

class Car:
  brand = ""
  color = ""
  max_speed= 0
  
  def __init__(self, brand,color,max_speed):
    self.brand = brand
    self.color = color
    self.max_speed = max_speed

# Instance object with initiate value
# Object 1
car1 = Car("Lexus","White",400)
# Object 2
car2 = Car("Toyota","Black",450)

# Print different info from same Class Car
print (f"{car1.brand} {car1.color} {car1.max_speed}")
print (f"{car2.brand} {car2.color} {car2.max_speed}")

Output #1

Lexus White 400
Toyota Black 450

2.3 Delete Object Property

In some reason you might want to remove a property from an Object. Remove an object is individual remove when instance different object. If we try to access deleted property, it will produce an error. We use keyword del to remove property.

Example #1

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

p1 = Person(11)
p2 = Person(22)

del p1.age
# output 22
print(p2.age)

# object p1 error to access property
print(p1.age)

Output #1

22

Traceback (most recent call last):
  File "main.py", line 13, in <module>
    print(p1.age)
AttributeError: 'Person' object has no attribute 'age'

2.3 Delete Object

We also can delete an object. We use keyword del to remove object. If we try to access deleted object, it will produce an error.

Example #1

class Person:
  x=0

p1 = Person()
p2 = Person()
del p1
print("p2 =>",p2)
# Error to use object p1
print("p1 =>",p1)

 Output #1

p2 => <__main__.Person object at 0x7f0bd50905b0>

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print("p1 =>",p1)
NameError: name 'p1' is not defined

It show an error which p1 Object was deleted.

Additional NOTE: Object and Class is mostly use in real word application, because it would maintained your code better and it is standard for every developers should follow. If you are fresh learner, I do recommend you to understand about Class and Object after learn all basic programming (Class & Object is the first step to move to Object Oriented).

Hope this article will help you learn how to create Object and Class in Python. Thanks

Python 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him