Python Classes/Objects

JK1982 
Created at
Updated at  

  7,251   0   0  

Python is object-oriented. In Python, most things are objects with properties and methods.

Class is an object constructor or "blueprint" for creating objects.


Create a Class

To create a class, use the keyword class:

class MyClass:
  x = 5

 

Create Object

Now we can use the class named MyClass to create objects:

p1 = MyClass()
print(p1.x)

 

The __init__() Function

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:

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

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

 

 

The __str__() Function

The __str__() function controls what should be returned when the class object is represented as a string.

If the __str__() function is not set, the string representation of the object is returned:

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

p1 = Person("John", 36)

print(p1)

 

Example Class

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

  def __str__(self):
    return f"{self.name}({self.age})"

p1 = Person("John", 36)

print(p1)

 

Object Methods

Objects can have methods. Methods are object-specific functions.

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()

 

The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:

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

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

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

 

Modify Object Properties

You can modify properties on objects like this:

p1.age = 40

 

Delete Object Properties

You can delete properties on objects by using the del keyword:

del p1.age

 

Delete Objects

You can delete objects by using the del keyword:

del p1

 

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

class Person:
  pass

 



Tags: Python Python Classes Python Objects Share on Facebook Share on X

◀ PREVIOUS
Python Arrays

▶ NEXT
Python Inheritance

  Comments 0
SIMILAR POSTS

Python Arrays

(updated at )

Python Lambda

(updated at )

Python Inheritance

(updated at )

Python Iterators

(updated at )

Python Functions

(updated at )

Python While Loops/For Loops

(updated at )

Python Conditions and If statements

(updated at )

Python Polymorphism

(updated at )

Python Scope

(updated at )

Python Modules

(updated at )

Python Dictionaries

(updated at )

Python Sets

(updated at )

Python Tuples

(updated at )

Python Comparison Operators

(updated at )

Python Arithmetic Operators

(created at )

Printing string n times

(created at )

String concatenation by join()

(created at )

Python Lists

(updated at )

Python String Operations

(updated at )

Python Data Types

(updated at )

Python Variables

(updated at )

Python Comments

(updated at )

Python Syntax

(updated at )

Python Getting Started

(updated at )

Python Introduction

(created at )

What is Python?

(updated at )

Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering

(updated at )

Machine Learning Types and Programming Languages

(updated at )

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship

(updated at )

Mastering Excel Data Manipulation with Python

(updated at )

Challenge: One Code Problem Per Day

(created at )

Clean Python Environments: The Power of venv vs. Docker

(updated at )

OTHER POSTS IN THE SAME CATEGORY

Clean Python Environments: The Power of venv vs. Docker

(updated at )

How to Build Llama 3 AI Apps with Python: Setup & User Prompts

(updated at )

Mastering Excel Data Manipulation with Python

(updated at )

Try...Catch Helps Ignoring Data Type Miss-Match Error in Python

(updated at )

RegExp example in Python to exclude javascript from HTML code

(created at )

Python code to convert from Lunar to Solar

(created at )

Python example to download webpage

(updated at )

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship

(updated at )

Python Modules

(updated at )

Python Scope

(updated at )

Python Polymorphism

(updated at )

Python Iterators

(updated at )

Python Inheritance

(updated at )

Python Arrays

(updated at )

Python Lambda

(updated at )

Python Functions

(updated at )

Python While Loops/For Loops

(updated at )

Python Conditions and If statements

(updated at )

Python Dictionaries

(updated at )

Python Sets

(updated at )

Python Tuples

(updated at )

Python Comparison Operators

(updated at )

Python Arithmetic Operators

(created at )

Printing string n times

(created at )

String concatenation by join()

(created at )

Python Lists

(updated at )

Python String Operations

(updated at )

Python Data Types

(updated at )

UPDATES

Harness vs. OpenClaw: Two Very Different "Agents"

(updated at )

Clean Python Environments: The Power of venv vs. Docker

(updated at )

What is Docker? Why is Docker also useful in a development environment?

(created at )

UIUC 2026-2027 Academic Calendar

(updated at )

How to Build Llama 3 AI Apps with Python: Setup & User Prompts

(updated at )

Open-Source LLMs: The AI Revolution

(updated at )

Resume 2.0: Leveling Up for My First Software Gig

(created at )

Not everyone will understand what this man just did

(created at )

UIUC Dorm Guide: Find Your Perfect Fit !!

(updated at )

Unpacking IU's Shopper

(created at )

Jackie Chan's Police Story: The Action Masterpiece

(updated at )

The IVE Story: Identity, 'I AM' Charts, and Influence

(updated at )

Tech Visionaries who graduated at UIUC - You are the Next Turn

(updated at )

Open Databases for Sex Crime Occurrences in the U.S.

(updated at )

Automatically copy text to the clipboard when dragging the mouse in the Cursor

(updated at )

My First Day at University of Illinois-Urvana Champaign

(updated at )

Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure

(updated at )

Sun, Rocks, and Adventure: A Day at Joshua Tree National Park

(updated at )

Sipping the Stars: My Starbucks Adventure

(updated at )

Exciting explore at Sequoia National Park

(updated at )

My Life Shot at Death Valley

(updated at )

Ip Man fights with Muay Thai Master

(created at )

Mad Clown - Don't Die

(created at )

How to get Student Enrollment and Degree Verification at UIUC

(updated at )

LAX Thanksgiving Rush: A Joyful Reunion

(updated at )

ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)

(updated at )

FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'

(updated at )

10CM - To Reach You (너에게 닿기를)

(updated at )

Feeling weak? Transform yourself at the UIUC ARC!

(updated at )

BOYNEXTDOOR - If I Say I Love You

(updated at )

The Future of Software Engineer - AI Engineering

(updated at )

G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025

(updated at )

Lie - Legend song by BIGBANG

(updated at )

Why ROLLBACK is useful when you work with Google Gemini CLI?

(created at )

Reimbursement after Vaccination at McKinley Health Center

(created at )

Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!

(created at )

Common Questions from UIUC school life in terms of CS Program

(created at )

UIUC Immunization Compliance

(created at )

LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...

(created at )

LEE CHANHYUK - Endangered Love (멸종위기사랑)

(created at )

Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)

(created at )

Common methods to improve coding skills

(created at )

US National Holiday in 2026

(created at )

BABYMONSTER “WE GO UP” Band LIVE [it's Live] K-POP live music show

(created at )

BLACKPINK - ‘Shut Down’ Live at Coachella 2023

(created at )

JENNIE - like JENNIE - One of Hot K-POP in 2025

(created at )

BABYMONSTER(베이비몬스터) - DRIP + HOT SOURCE + SHEESH

(created at )

Common Naming Format in Software Development

(created at )

In a life where I don't want to spill even a single sip of champagne - LEE CHANHYUK - Panorama(파노라마)

(created at )

Countries with more males and females - what about UIUC?

(created at )