Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Python Programming – Class

Networking for Software Developer


Narendra Pershad
te d,
r i e n
e c t-o
s o bj .”
m i oo d
o g ra i s g
d p r r am
g o o rog
y d p
ever e nt e
n o t
t-o ri
a i nly b j e c
e rt y o
“ C
o t eve r
d n p
an tr u
tr o us
r neS
Bj a
Agenda
• What is a class?

• Anatomy of a class
• Different members of a class

• How to use a use class

• Advanced class concepts:


• overloading

• Inheritance

• DataClass

• This will not be a formal treatment of OOP but to link your knowledge of OOP with python.
What is a class?

• A piece of self-contained software having the following:

• Attribute or Properties (this corresponds to C# fields)

• Constructor

• Methods (these are functions that lives in a class)

• All members are public by default.


• A member prefix with __ regarded as private
• A member prefix with _ regarded as protected
• Class members
Why classes?
• Helps in software development
• An application can be modeled as a tasks are decomposed into smaller ones
• Smaller tasks are easier to
• Implement

• Troubleshoot

• Debug

• Use

• To chain to achieve more involved interaction

• Coder can concentrate on a smaller part of the solution


• Can clearly understand the purpose of each unit (method)
• Can define clear inputs and outputs

• Functions should have a single responsibility


class Person:
"""
This is a python class.
"""

_id = 100000 #class variable

def __init__(self, name): #constructor of any class is __init__


"""
Initializes an object of this class.
"""
self.name = name #define a python property name
self.id = Person._id #assigs a unique value to the attribute
Person._id += 1 #increments the class variable class

a = Person( 'Narendra' ) #notice the absence of the new keyword


print(a) #<__main__.Person object at 0x102f2b2e8>
#later we will learn how to change this
Operator overloading
• Object by default does not have logic for comparison operator
• The default behavior for the == is not the preferred one
• For mathematical object the arithmetic operators are important

• The following operator can be overloaded:


• Comparision:
==, !=, >, <, <=, >=

• Mathematical:
+, -, *, /, //, %, **

• Assignment:
-=, +=, *=, /=, //=, **=

• Unary:
-, +, ~

• Another behavior that you might want to modify is when an object in printed
• This is can be done be defining a method of the form
__str__(self):
def __str__(self):
"""
Return a string representation of this object.
"""
return f'{self.id}: {self.name}'

def __eq__(self, other):


"""
Overrides the == operator.
"""
return self.name == other.name

a = Person('Narendra') #instantiate a object


print(a) #100000: Narendra
b = Person('Narendra') #instantiate another object
print(f'{a} {"=" if a==b else "!="} {b}') #100000: Narendra = 100001: Narendra
Adding and removing attributes from objects
>>> a = Person('Narendra') #instantiate a object

>>> print(a) # [3, 4i]


>>> a.title = 'Professor' #adds an attribute to a (this is not possible in c#)

>>> print(a) # [3, 4i]


>>> print(a.title) #Professor

>>> del(a.title) #remove an attribute from a


>>> a.title #AttributeError: 'Person' object has no attribute 'title'

>>> del(a) #remove a (again not possible in C#)


>>> a #NameError: name 'a' is not defined
Inheritance

• Inheritance allows you to use logic from another class

• Python support multiple inheritance

• C# only support single inheritance

• Inheritance is transitive

• If A is the parent of B and B is the parent of C, then A is also the parent of C


class Person:
def __init__(self, name): #constructor of the Person class
self.name = name #define a python attribute name

def __str__(self):
return self.name

class Student(Person):
def __init__(self, name, program):
Person.__init__(self, name) #calls the parent constructor
super().__init__( name ) #this is equivalent to the line above
self.program = program #define its own attribute

def __str__(self):
return f'{self.name} is enrolled in {self.program}'
class Person:
d it
def __init__(self, name): an
ated
self.name = name p lic e.
co m urs
e is is co
a c
n n th
i t
class Employee:
h er red i
def __init__(self, department): le in ove
lti p e c
M u l n ot b
self.department = department
wil

class Faculty(Person, Employee):


def __init__(self, name, department, salary):
Person.__init__(self, name) #calls the person constructor
Employee.__init__(self, department) #calls the employee constructor
self.salary = salary #define its own attribute
Abstract class
from abc import ABC, abstractmethod
class Moveable(ABC):
'''
Move method is declare abstract,
so the entire class will be abstract
'''
@abstractmethod
def move(self):
pass

>>> a = Moveable()
TypeError: Can't instantiate abstract class Moveable with abstract methods move
Summary

• Classes is a core feature of OOP

• Classes may have class variables, methods, as well as instance variables and methods.

• You are allowed to overload operators

• Like javascript and unlike C# you can add and remove attributes (both variables and methods)
dynamically to an object.

• Python supports the questionable multiple inheritance

You might also like