A Simple Guide to Create Private Methods and Properties in Python Class – Python Tutorial

By | August 26, 2019

Methods and properties are public defaultly in python class, however, how to create private methods and properties in a python class? In this tutorial, we will tell you how to create.

Create a common python class

class Car:
  #Constructor to initialize
  def __init__(self, price,color):
      self.price = price
      self.color = color

  #function to print car price and color
  def display(self):
      print ('This car is', self.color, self.price)

In this python class Car, here are two public properties (price and color) and a public method (display), we can create a car object to access them.

car_obj = Car(12345, 'red')
car_obj.display()
color = car_obj.color
print(color)

The result is:

This car is red 12345
red

However, if you want to create a private property and method in this class,  you can do like this:

def __method_name(parameters):
    pass
__variable_name = value

Create a private property: price

class Car:
  #Constructor to initialize
  def __init__(self, price,color):
      self.__price = price
      self.color = color
      #self.__setInfo(125, 'blue')

  #function to print car price and color
  def display(self):
      print ('This car is', self.color, self.__price)

Then we can not use a car object to access price property.

car_obj = Car(12345, 'red')
car_obj.display()
price = car_obj.__price
print(price)

You will get error:

python class private property

Create a private method:__setInfo()

Here we create a private method, then we can not use a car object to access it.

class Car:
  #Constructor to initialize
  def __init__(self, price,color):
      self.__price = price
      self.color = color
      self.__setInfo(125, 'blue')

  #function to print car price and color
  def display(self):
      print ('This car is', self.color, self.__price)
    
  def __setInfo(self, price, color):
      self.__price = price
      self.color = color

Then execute these code.

car_obj = Car(12345, 'red')
car_obj.display()

car_obj.__setInfo(125, 'blue')

You will get this error:

python class private method

Leave a Reply