Make delicious recipes!

Classes in Python


Basic idea behind classes and objects in python is very similar to other languages but the syntax is different.
For example, constructors are declared with the method __init__(),
data members can be added or deleted dynamically,
functions inside a class are treated more like variables and can be assigned to objects outside the class.

Example:

class foo:
  
  # a field in the class
  bar = "a variable inside class"
  
  # a member function of the class
  def func (self):
    print ("my variable is - " + self.bar)
  
  # When the method __init__() is defined in a class, 
  # instantiation of the class automatically invokes this method.
  # So this acts like a constructor in C++ / Java
  def __init__(self, a, b):
    self.var1 = a
    self.var2 = b



# Object instantiation in Python
instanceVar = foo(5,6)

# Properties can be added to the instance after instantiation also
instanceVar.var3 = "Hello"


print ( instanceVar.var1 )
# Output: 5
print ( instanceVar.var2 )
# Output: 6
print ( instanceVar.var3 )
# Output: Hello


# Functions inside a variable can be called as in other languages.
instanceVar.func()
# Output: my variable is a variable inside class


# It is possible to get a reference to the class functions and call
# those functions only from the reference.
fooFunc = foo.func
fooFunc(instanceVar)
# Output: my variable is a variable inside class


# Use 'del' to remove members from an instance
del instanceVar.var1
print (instanceVar.var1)
#Output:
#Traceback (most recent call last):
#  File "", line 1, in 
#AttributeError: 'foo' object has no attribute 'var1'


Note: The copy paste from the above may remove the indentation spaces due to which python can give indentation errors. If such a thing happens, then indentation spaces have to be put manually after copy-paste.


The variable 'self': The name self has no special meaning in Python.
It is just a convention to make self as the first argument in a class.



Inheritance


Python supports multiple inheritance by making use of the following syntax:


# declare first base class
class base1:
  var1 = 5
  def func1 (self):
    return self.var1


# declare second base class
class base2:
  var2 = 10
  def func2 (self):
    return self.var2


# followin class derives from both base1 and base2
class drvd (base1, base2):
  def func (self):
    return self.func1() + self.func2()


# we instantiate the derived class here
obj = drvd()

# both the below statements print 15
print (obj.func())
print (obj.var1 + obj.var2)



Private: Python does not have a concept of private variables but by convention, any variable starting with an underscore is considered private.

Empty class: Finally, to create an empty class, use the following syntax.
(Such a class resembles the struct construct in C)

class rec:
  pass
  
foo = rec()
foo.name = "Tom"
foo.age = 30
foo.height = 5.5



Customizing the default string representation of an object


If an object is printed by default, it prints the memory address of the object.
While this is useful in many cases, sometimes it is desired to customize this default string representation.
This can be done by over-riding __str__(self) function in a class.
Java programmers can relate this to the toString() function.
Example:

##################################################
# Default string representation of an object 
##################################################
class foo:
  def __init__(self, a, b):
    self.a = a
    self.b = b


obj = foo(4,5)
print (obj)
# Output:
# <__main__.foo object at 0x00000000028D5358>


#########################################################################################
# By over-riding the __str__(self) function, the string representation can be customized 
#########################################################################################
class foo:
  def __init__(self, a, b):
    self.a = a
    self.b = b
  def __str__ (self):
    return "Object of type: " + str(self.__class__) + "\n" + "Members: a=" + str(self.a) + ", b=" + str(self.b)


obj = foo(4,5)
print (obj)
# Output:
# Object of type: <class '__main__.foo'>
# Members: a=4, b=5








Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal