SimpleTuts.com

Python Class and Objects

In Python, a class is a blueprint or a template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have. Classes facilitate object-oriented programming principles like encapsulation, inheritance, and polymorphism, allowing for structured and reusable code.

An object in Python is a concrete instance of a class, possessing its own state (attributes) and behavior (methods).


class Person:               #Creates a class named Person
  def __init__(self, myname, myage):
    self.name = myname
    self.age = myage

p1 = Person("John", 36)    #Creates an object p1 of class Person

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

p2 = Person("Jane", 28)    #Creates an object p2 of class Person

print(p2.name)
print(p2.age)
                
Python Online Compiler

Object with functions


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

  def myfunc1(self):
    print("Hello my name is " + self.name)
    
  def myfunc2(self):
    print("I am " + str(self.age) + " years old")

p1 = Person("John", 36)
p1.myfunc1()
p1.myfunc2()

p2 = Person("Jane", 28)
p2.myfunc1()
p2.myfunc2()



                
Python Online Compiler