DEV Community

Max
Max

Posted on

Python classes and objects tutorial

Python is a object oriented programming language, it supports class and objects.

  1. class name should start with first letter as caps.
  2. variables inside a class are called as attributes.
  3. function inside a class are called as methods.
  4. self keyword is used to refer the attributes and methods that belongs to the class, using the self we can directly access the attribute and method inside the class.

simple class syntax:

class Myclass():
   pass
Enter fullscreen mode Exit fullscreen mode

Class constructor

class Myclass():
   def __init__(self):
      pass
Enter fullscreen mode Exit fullscreen mode

init is a special method in python which as a constructor, it will be called when declaring an object.

Declaring a class object

class Myclass():
   def __init__(self):
      print("I'm Constructor")

myObject = Myclass()

Output:
I'm Constructor
Enter fullscreen mode Exit fullscreen mode

by default constructor method get called, we are not directly calling any method in the class.

Passing value to constructor

class Myclass():
   def __init__(self, x, y):
      print("I'm Constructor")
      print("x:", x)
      print("y:", y)

myObject = Myclass(5, 10)

Output:
I'm Constructor
x: 5
y: 10
Enter fullscreen mode Exit fullscreen mode

Assign value to class attributes

class Myclass():
   def __init__(self, x, y):
      self.x = x
      self.y = y

myObject = Myclass(5, 10)
Enter fullscreen mode Exit fullscreen mode

even thought the argument x and self.x looks same but they are different, self is used to refer the attribute belong to the class, argument x is only accessible inside the init block.

Class Methods

class Myclass():
   def __init__(self, x, y):
      self.x = x
      self.y = y

   def access(self):
       print("x:", self.x)
       print("y:", self.y)

myObject = Myclass(5, 10)
myObject.access()

Output:
x: 5
y: 10
Enter fullscreen mode Exit fullscreen mode

value for x and y are assigned in the constructor function even though it can be accessed anywhere inside the class since it belong to the class.

Create multiple class objects

class Myclass():
   def __init__(self, x, y):
      self.x = x
      self.y = y

   def access(self):
       print("x:", self.x)
       print("y:", self.y)

myObject1 = Myclass(5, 10)
myObject1.access()

myObject2 = Myclass(20, 30)
myObject2.access()

Output:
x: 5
y: 10
x: 20
y: 30
Enter fullscreen mode Exit fullscreen mode

Consider the objects as storage space, any action made to the object only belongs to it, it won't affects other objects.

Explore Other Related Articles

Python Recursion Function Tutorial
Python Lambda Function Tutorial
Python If, If-Else Statements Tutorial
Python Function Tutorial
Python break and continue tutorial
Python While Loop tutorial

Top comments (0)