Built-In & More Classes & Objects

In last 2 chapter, we learnt about some usage of class, self, and basic how-to. In this chapter, we will look in to more depth of python. Let's start with an Example :-

#!/usr/bin/python

class Employee:
   numEmployee = 0

   def __init__(self, name, employeeRole , salary):
      self.name = name
      self.employeeRole = employeeRole
      self.salary = salary
      Employee.numEmployee += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.numEmployee

   def displayEmployee(self):
      print "Employee Name : ", self.name,  ", He is ", self.employeeRole, " with Salary: ", self.salary
  • The variable numEmployee is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.numEmployee from inside the class or outside the class.

  • The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.

  • You declare other class methods like normal functions with the exception that the first argument to each method is self.  As learnt in last chapter, Classes in python itself is an object and it's first parameter is reference to self or to an object, if you didn't read about self, yet, go back and read it first. you will have much understanding about it.

Creatng an instance of this object

Now, here , we have __init__ as class constructor, which takes argument. So this time, whenever we create an instance of the class, we need to make sure, we also pass required arguments.

//This would create first object of Employee class

emp1 = Employee("Rocky", "Developer", 2000)

// Creating Second object of Employee class

emp2 = Employee("facebook", "Marketing Analyst", 5000)

So, now in above , you can see, we have initialised class with various arguments and each object has it's own value.

You can also add, remove, or modify attributes of classes and objects at any time like below :-

Add Attribute

emp1.experience = 9  # Add 'experience' attribute.
emp2.experience = 8  # Add 'experience' attribute.

Edit / Modify Attribute

emp1.experience = 12  # Modify 'experience' attribute.
emp2.experience = 10  # Modify 'experience' attribute.

Del Attribute

del emp2.experience   # Deletes 'experience' attribute of second employee

Instead of using the normal statements to access attributes, you can use the following functions ?

  • The getattr(obj, name[, default]) : to access the attribute of object.

  • The hasattr(obj,name) : to check if an attribute exists or not.

  • The setattr(obj,name,value) : to set an attribute. If attribute does not exist, then it would be created.

  • The delattr(obj, name) : to delete an attribute.

hasattr(emp1, 'experience')    # Returns true if 'experience' attribute exists
getattr(emp1, 'experience')    # Returns value of 'experience' attribute
setattr(emp1, 'experience', 8) # Set attribute 'experience' at 8
delattr(empl, 'experience')    # Delete attribute 'experience'

Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute ?

  • __dict__: Dictionary containing the class's namespace.

  • __doc__: Class documentation string or none, if undefined.

  • __name__: Class name.

  • __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode.

  • __bases__: A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

For the above class let us try to access all these attributes ?

#!/usr/bin/python

class Employee:
   numEmployee = 0

   def __init__(self, name, employeeRole , salary):
      self.name = name
      self.employeeRole = employeeRole
      self.salary = salary
      Employee.numEmployee += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.numEmployee

   def displayEmployee(self):
      print "Employee Name : ", self.name,  ", He is ", self.employeeRole, " with Salary: ", self.salary


print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

Result

Employee.__doc__: None
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0x7f23bc0bf758>, 'numEmployee': 0, 'displayEmployee': <function displayEmployee at 0x7f23bc0bf7d0>, '__doc__': None, '__init__': <function __init__ at 0x7f23bc0bf6e0>}

Destroying Objects or Garbage Collection

Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection. 

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

a = 90      # Create object <90>

b = a       # Increase ref. count  of <90>

c = [b]     # Increase ref. count  of <90> 

del a       # Decrease ref. count  of <90>

b = 100     # Decrease ref. count  of <90> 

c[0] = -1   # Decrease ref. count  of <90> 

You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method can be used to clean up any non memory resources used by an instance.

Example :
#!/usr/bin/python

class Employee:
   def __init( self, name='Rocky Sharma', experience=0):
      self.name = name
      self.experience = experience

   def __del__(self):
      class_name = self.__class__.__name__
      print class_name, "destroyed"

emp1 = Employee()
emp2 = emp1
emp3 = emp1

print id(emp1), id(emp2), id(emp3) # prints the ids of the obejcts

del emp1
del emp2
del emp3

Result

140054265005840 140054265005840 140054265005840
Employee destroyed

Note: Ideally, you should define your classes in separate file, then you should import them in your main program file using import statement. We will learn about module and package in our next class.

Class Inheritance

Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Syntax :

class SecondaryClass (ParentClass1 , ParentClass2, [...]):
   rest_of_the_class

Example

#!/usr/bin/python

class ParentClass:        # define parent class
   parentAttribute = 100

   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      ParentClass.parentAttribute = attr

   def getAttr(self):
      print "Parent attribute :", ParentClass.parentAttribute

class ChildClass(ParentClass): # define child class
   def __init__(self):
      print "Calling child constructor"

   def childMethod(self):
      print 'Calling child method'

c = ChildClass()          # instance of child
c.childMethod()           # child calls its method
c.parentMethod()          # calls parent's method
c.setAttr(200)            # again call parent's method
c.getAttr()               # again call parent's method

Result

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

  • The issubclass(sub, sup) boolean function returns true if the given subclasssub is indeed a subclass of the superclass sup.

  • The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class

Overriding Methods

You can always override your parent class methods. if you need special or different functionality in your subclass.

#!/usr/bin/python

class Parent:        # define parent class
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method

Result

Calling child method

Base Overloading Methods

Following table lists some generic functionality that you can override in your own classes.

SN Method, Description & Sample Call
1 __init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2 __del__( self )
Destructor, deletes an object
Sample Call : del obj
3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)
4 __str__( self )
Printable string representation
Sample Call : str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Overloading Operators

You could, define the __add__ method in your class to perform vector addition.

Example 

#!/usr/bin/python

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2

Result

Vector(7,8)

Data Hiding

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.

#!/usr/bin/python

class CounterProgram:
   __hiddenCount = 0
  
   def count(self):
      self.__hiddenCount += 1
      print self.__hiddenCount

counter = CounterProgram()
counter.count()
counter.count()
print counter.__hiddenCount    # Direct access is not available

Result

1
2
Traceback (most recent call last):
  File "data.py", line 13, in <module>
    print counter.__hiddenCount    # Direct access is not available until used with class name
AttributeError: CounterProgram instance has no attribute '__hiddenCount'

Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you ?

print counter._CounterProgram__hiddenCount

Above would have given you result of 

2

 


Loading ...

Related Results :

  1. [How-to] Setup Custom full root or Sub-Domain for Profile and Course
  2. Introduction to HTML
  3. HTML Basic Tags and Elements
  4. HTML Attributes
  5. HTML Formatting
  6. HTML Phrase Formatting
  7. HTML Comment Tags
  8. HTML Meta and OG (Opengraph) Tags
  9. HTML Images
  10. HTML Tables
  11. HTML Lists
  12. Introduction to Python
  13. Variables and Types
  14. Lists, Tuples & Dictionary
  15. Basic Operators
  16. If else-elif else nested if Statement
  17. For & While Loops
  18. String Formatting
  19. Functions in Python
  20. Basic String Operations
  21. Classes and Objects
  22. self in python class
  23. Built-In & More Classes & Objects
  24. Modules and Packages
  25. Introduction to CSS
  26. CSS Syntax & Selectors
  27. Include CSS
  28. CSS Measuring Units
  29. CSS Colors
  30. CSS - Background
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author