Python Tutorial Series – Classes

In object oriented programming, classes are used as a blueprint to define objects in an application. Classes are a way to organize code, provide the ability to easily extend functionality and allow for reuse.

In Python, a class is defined as follows:



class BaseClass:
  # constructor
  def __init__(self, param1):
    self.param1 = param1
    self._aprotectedvariable = 1
    self.__aprivatevariable = 2
 
  def set_param1(self, param1):
    self.param1 = param1

  def get_param1(self):
    return self.param1

  def who_am_i(self):
    print('I am a Base Class')

  def _a_protected_method(self):
    print('I am a protected method')
 
  def __a_private_method(self):
    print('I am a private method')

  private_method = __a_private_method


Class names are camel cased, which means each word starts with a capital letter and there are no underscores.


Variable/Method Scope:

Protected variables and methods are defined by adding one underscore to the beginning of the variable or method name. Protected variables and methods are still accessible outside of the class. However, a best practice is not to access either one and to use caution if it really needs to be done.
Private variables and methods are defined by adding two underscores to the beginning of the variable name. Private variable and method names are mangled, so they are not as easy to access outside of the class. It can still be done by calling a variable as _class__variable, ex: _BaseClass__aprivatevariable. This should never really be done though.
A class may also provide access to private or protected members by assigning a public variable to them, which is what the line:



private_method = __a_private_method


is doing.


Inheritance:

A child class can be created as follows:



class ChildClassA(BaseClass):
  def __init__(self, parama, paramb):
    super().__init__(parama)
    self.param2 = paramb
 
  def who_am_i(self):
    print('I am a Child Class A')


The who_am_i method demonstrates how a child class can override a method in a parent class.


Example Usage:

A class is instantiated as follows:



base_class = BaseClass('abc')
base_class.who_am_i()
base_class.private_method()
base_class._BaseClass__a_private_method()
print(base_class._BaseClass__aprivatevariable)

child_class_a = ChildClassA('123', '456')
child_class_a.who_am_i()




More Python











 

Comments