Sunteți pe pagina 1din 15

Python Programming –

Class/Object, Package and Coding


Style

July - 2018

Copyright © 2018 Aricent. All rights reserved.


Agenda

1. Python Class Definition Syntax

2. Class Instantiation and Method Objects

3. Inheritance

4. Operator Overloading

5. Abstract Base Class

6. Private Variables and Name Mangling

7. Python Packages

8. Python Coding Guidelines

9. Static Code Analysis

Copyright © 2018 Aricent. All rights reserved. 2


Python Classes

Class Definition Syntax

class DemoClass:
"""A simple demonstration class Testing ...."""
#class variable, shared by all instances
no_of_instances = 0

def __init__(self, name):


#name on the left and name on the right are different
if name:
self.name = name
else:
self.name = "default"
DemoClass.no_of_instances += 1

def die(self):
print(self.name, "! getting destroyed")
DemoClass.no_of_instances -= 1

def sayhi(self):
print("Hi!! I am ", self.name)

Points to Note:

a) A new class is created using the “class” statement and name of the class
b) This is followed by an indented block of statements (usually function definitions) which form the body of the class
c) Class definitions must be executed before they have any effect.
d) When a class definition is interpreted, a “class object” is created.
e) Instance variables (here “name”) are for data unique to each instance and class variables are for attributes and methods shared by all
instances of the class: (https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables)
f) When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.
g) A method function is declared with an explicit first argument representing the object, which is provided implicitly by the call. Often, the
first argument of a method is called self. This is just a convention.

Copyright © 2018 Aricent. All rights reserved. 3


Python Classes

Class Instantiation and Method objects

def main():
"""main function. Testing ....."""
x = DemoClass("object1")
y = DemoClass("object2")
z = DemoClass("")
print(y.no_of_instances)
y.sayhi()
x.sayhi()
#z.sayhi()
DemoClass.sayhi(z)
x.die()
print(y.no_of_instances)
print(type(DemoClass))
print(type(z))

if __name__ == "__main__":
main()

Points to note
• x = DemoClass("object1") -> creates a new instance of the class and assigns this object to the local variable x.
• Class instantiation automatically invokes __init__() for the newly-created class instance
• x.sayhi() -> The method sayhi is called
• Even though the function definition for “sayhi” specified an argument it was called without the argument
• In this example, the call x.sayhi() is exactly equivalent to DemoClass. sayhi(x)

Copyright © 2018 Aricent. All rights reserved. 4


Python Classes
Inheritance:

• In most class-based object-oriented languages, an object created through inheritance (a "child object") acquires all the properties
and behaviors of the parent object.
• One of the major benefits of object oriented programming is reuse of code and one of the ways this is achieved is through the
inheritance mechanism.

The Python syntax for a derived class definition looks like this:

class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>

Points to Note:
• The name BaseClassName must be defined in a scope containing the derived class definition
• When the class object is instantiated, the base class is remembered. This is used for resolving attribute references: if a
requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the
base class itself is derived from some other class.
• Derived classes may override methods of their base classes
• An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the
same name.

Reference: https://docs.python.org/3/tutorial/classes.html#inheritance

Copyright © 2018 Aricent. All rights reserved. 5


Python Classes
An example of Inheritance
class SchoolMember:
"""Represents any school member."""
def __init__(self, name, age):
self.name = name
self.age = age
print("Initialized {} as SchoolMember".format(self.name))
def tell(self):
"""Tell my details."""
print("Name:{} Age:{}".format(self.name, self.age))

class Teacher(SchoolMember): class Student(SchoolMember):


"""Represents a teacher.""" """Represents a student."""
def __init__(self, name, age, salary): def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age) SchoolMember.__init__(self, name, age)
self.salary = salary self.marks = marks
print("Initialized {} as Teacher".format(self.name)) print("Initialized {} as Student".format(self.name))
def tell(self): def tell(self):
SchoolMember.tell(self) SchoolMember.tell(self)
print("Salary: {}".format(self.salary)) print("Marks: {}".format(self.marks))

#============================================================
# main function getting defined below
#============================================================

def main():
"""main function."""
t = Teacher('Anurag', 40, 30000)
s = Student('Avishek', 25, 75)
print("####################################")
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students

# Entry point of the script


if __name__ == "__main__":
main()
Copyright © 2018 Aricent. All rights reserved. 6
Python Classes

Operator Overloading

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing)
by defining methods with special names.
This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.

class Point: Points to Note:


"""Defining a point in cartesian coordinate"""
a) Addition is overloaded for this example
def __init__(self, x = 0, y = 0): b) “__add__” method is called to implement arithmetic addition
self.x = x
(List of other methods can be referred from
self.y = y
https://docs.python.org/3/reference/datamodel.html#emulating-numeric-
types)
def __add__(self,other):
"""overloading addition""" a) “__str__” computes the “informal” or nicely printable string representation of
x = self.x + other.x
an object. If this is not Implemented, in this case, print(p3) will only print the
y = self.y + other.y
return Point(x,y) address of the object.

def __str__(self):
"""Customizing __str__"""
return "[{},{}]".format(self.x,self.y)

p1 = Point(2,3)
p2 = Point(-1,2)
p3 = p1 + p2
print(p3)

Copyright © 2018 Aricent. All rights reserved. 7


Python Classes
Abstract Base Class
• Abstract classes cannot be instantiated, but they can be sub classed.
• An abstract method is a method that is declared without an implementation
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
class myshape(ABC): class myshape(ABC):
"""An ABC""" """An ABC"""
@abstractmethod @abstractmethod
def area(): def area():
pass pass

@abstractmethod @abstractmethod
def perimeter(): def perimeter():
pass pass
Output:
20
class Rectangle(myshape): class Rectangle(myshape):
18
"""Derived Class""" """Derived Class"""
def __init__(self, w, h): def __init__(self, w, h):
self.w = w self.w = w
self.h = h Output: self.h = h
TypeError: Can't
def area(self): instantiate abstract def area(self):
return self.w * self.h class myshape with return self.w * self.h
abstract methods area,
def perimeter(self): perimeter def perimeter(self):
return 2 * self.w + 2 * self.h return 2 * self.w + 2 * self.h

myrect = Rectangle(4, 5) a = myshape()


print(myrect.area())
print(myrect.perimeter())

Points to note:
• abc module is to be used to create abstract classes (https://docs.python.org/3/library/abc.html)
• The abstractmethod decorator is used to declare a method abstract (https://docs.python.org/3/library/abc.html#abc.abstractmethod)
• The class is made abstract by inheriting from a helper class “ABC” (For Python 3.4+).
• For lower version of Python, check the syntax from StackOverflow
• For use of abstract base classes in Python refer StackOverflow
Copyright © 2018 Aricent. All rights reserved. 8
Python Classes

Private Variables
Private” instance variables that cannot be accessed except from inside an object don’t exist in Python.
However, there is a convention that is followed by most Python code: a name prefixed with an underscore should be treated as a
non-public part of the API (whether it is a function, a method or a data member).
It should be considered an implementation detail and subject to change without notice.

Name mangling
Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses),
there is limited support for such a mechanism, called name mangling.
Any identifier of the form __var (at least two leading underscores, at most one trailing underscore) is textually replaced with
_classname__var, where classname is the current class name with leading underscore(s) stripped

class Foo(): class Foo():


def __init__(self): def __init__(self):
self.__baz = 66 Used baz instead of __baz self.baz = 66
def foo(self): def foo(self):
print(self.__baz) print(self.baz)

class Bar(Foo): Output


class Bar(Foo):
def __init__(self): def __init__(self):
super(Bar, self).__init__() 33
super(Bar, self).__init__()
self.__baz = 33 33
self.baz = 33
def bar(self): {'baz': 33}
def bar(self):
print(self.__baz) print(self.baz)
Output
x = Bar() x = Bar()
x.foo() 66 x.foo()
x.bar() 33 x.bar()
print(x.__dict__) {'_Foo__baz’: 66, '_Bar__baz’: 33} print(x.__dict__)

Copyright © 2018 Aricent. All rights reserved. 9


Python Packages

Why do we need packages?

• Packages are a way of structuring Python’s module namespace by using “dotted module names”
(For example, the module name A.B designates a submodule named B in a package named A)
• The use of dotted module names saves the authors of multi-module packages from having to worry about each
other’s module names.
(Modules like html.parser and email.parser and dateutil.parser all have unique names though the authors of the
modules used the same name “parser”)

mypackage/ Points to Note:


__init__.py a) A directory structure of an arbitrary package is shown
b) The __init__.py files are required to make Python treat the directories
file1.py as containing packages;
file2.py c) In the simplest case, __init__.py can just be an empty file, but it can
mysubpackage/ also execute initialization code for the package. When importing the
__init__.py package,
submodule1.py d) Python searches through the directories on sys.path looking for the
submodule2.py package subdirectory.

Copyright © 2018 Aricent. All rights reserved. 10


An example of Python Package

Local directory path\demo_pkg Local directory path\demo_pkg\mymainpkg


mymainpkg Directory/folder mysubpkg1 Directory/folder
pkg_mymain.py mysubpkg2 Directory/folder
__init__.py
"""Caller Module"""
print("Initialising Mymainpkg")
from mymainpkg.mysubpkg1 import subpkg1mod1
from mymainpkg.mysubpkg2 import subpkg2mod1
Local directory path\demo_pkg\mysubpkg1
def main(): __init__.py
"""main function"""
subpkg1mod1.func1() print("Initialising SubPkg1")
subpkg1mod1.func2()
subpkg2mod1.func1() subpkg1mod1.py

if __name__ == "__main__": """Demo for ACP"""


main() def func1():
"""First Function"""
print("SubPkg1 - fun1")

Output def func2():


"""Second Function"""
Initialising Mymainpkg print("SubPkg1 - fun2")
Initialising SubPkg1
Initialising SubPkg2 Local directory path\demo_pkg\mysubpkg2
SubPkg1 - fun1 __init__.py
SubPkg1 - fun2
SubPkg2 - fun1 print("Initialising SubPkg1")

subpkg2mod1.py

"""Demo for ACP"""


def func1():
"""First Function"""
print("SubPkg2 - fun1")

Copyright © 2018 Aricent. All rights reserved. 11


Python Coding Guidelines

Why do we need Coding Guidelines?

• Code is read much more often than it is written!!


• A well written code improves the readability and make it consistent across the wide spectrum of codes
• A style guide is about consistency
➢ Consistency with the style guide is important
➢ Consistency within a project is more important
➢ Consistency within one module or function is the most important

Please go through the references below for a detailed discussion.


1. https://www.python.org/dev/peps/pep-0008/
2. https://github.com/google/styleguide/blob/gh-pages/pyguide.md

Few important python coding guidelines are mentioned below

• Use 4-space indentation, and no tabs.


• Wrap lines so that they don’t exceed 79 characters.
• Use blank lines to separate functions and classes, and larger blocks of code inside functions.
• When possible, put comments on a line of their own.
• Use docstrings.
• Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).
• Name the classes and functions consistently
• The convention is to use CamelCase for classes and lower_case_with_underscores for functions and method
• Always use self as the name for the first method argument

Copyright © 2018 Aricent. All rights reserved. 12


Static Code Analysis

Static Code Analysis is the analysis of computer software that is performed without actually executing programs.
Usually a tool (generally called linter) is used for this. A Lint or a Linter is a program that supports linting (verifying code
quality)

Following reports are typically provided by Static Analyzers


▪ Warnings about syntax errors
▪ Non Adherence to Coding Standard
▪ Duplicated Code
▪ Suspicious constructs

Static Analyzers are especially useful for interpreted languages like Python. Because such languages lack a compiling
phase that displays a list of errors prior to execution.

Few Python Source Code Analyzers are mentioned below

• PyLint (https://www.pylint.org/)
• Pyflakes (https://pypi.org/project/pyflakes/)
• Pychecker (http://pychecker.sourceforge.net/) Note: Works for Python 2.7 and below.

Copyright © 2018 Aricent. All rights reserved. 13


Thank You
Headquarters
3979 Freedom Circle
Santa Clara, CA 95054
www.aricent.com

Copyright © 2018 Aricent. All rights reserved.


Revision History

Revision no. Date Description of change Author Reviewed and Approved By

1.0 16-Jul-2018 Initial creation Virat Gupta Tanmoy Bandyopadhyay

Copyright © 2018 Aricent. All rights reserved. 15

S-ar putea să vă placă și