Python OOP Part 2
In Python, we use double underscore (Or __) before the
attributes name and those attributes will not be directly visible outside.
We can access the value of hidden attribute by a tricky
syntax.
Private methods are accessible outside their class, just not
easily accessible. Nothing in Python is truly
private; internally, the names of private methods and
attributes are mangled and unmangled on the fly to make them seem inaccessible
by their given names.
Printing objects gives us information about objects we are
working with. In C++, we can do this by adding a friend ostream& operator
<< (ostream&, const Foobar&) method for the class. In Java, we
use toString() method. In python this can be achieved by using __repr__ or
__str__ methods.
class Test:
def __init__(self,
a, b):
self.a = a
self.b = b
def __repr__(self):
return
"Test a:%s b:%s" % (self.a, self.b)
def __str__(self):
return
"From str method of Test: a is %s," \
"b
is %s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t) # This calls __str__()
print([t]) # This calls __repr__()
If no __str__ method is defined, print t (or print str(t))
uses __repr__.
If no __repr__ method is defined then the default is used.
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.
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.
Example:
class Student:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
s = Student ('Piyush')
s.say_hi()
# The previous 2
lines can also be written as
# Student('Piyush').say_hi()
Class variables are shared - they can be accessed by all instances of that
class. There is only one copy of the class variable and when any one object
makes a change to a class variable, that change will be seen by all the other
instances.
Object variables are owned by each individual object/instance of the class.
In this case, each object has its own copy of the field i.e. they are not
shared and are not related in any way to the field by the same name in a
different instance.
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 subclass sub 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
Multiple Inheritance
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
Example:
class X(object):
def __init__(self, a):
self.num = a
def doubleup(self):
self.num *= 2
class Y(X):
def __init__(self,a):
X.__init__(self, a)
def tripleup(self):
self.num *= 3
obj = Y(4)
print(obj.num)
obj.doubleup()
print(obj.num)
obj.tripleup()
print(obj.num)
Output:
4
8
24
Comments
Post a Comment