Skip to content

Classes and Objects

In Python, you create a class using the class keyword.

Creating a Class

class MyClass:
  x = 5

Creating an Object

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

p1 = MyClass()
print(p1.x) # 5

The self Parameter

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

It must be the first parameter of any function in the class, but you can call it whatever you like (though self is the industry standard).

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

  def myfunc(abc): # Here 'abc' is used instead of 'self'
    print("Hello my name is " + abc.name)

p1 = Person("Vishnu", 25)
p1.myfunc()

Modifying Object Properties

You can modify properties on objects like this: p1.age = 30. You can also delete properties or objects using the del keyword: del p1.age or del p1.