Professional Documents
Culture Documents
Module01 Wk02a Classes
Module01 Wk02a Classes
• Anatomy of a class
• Different members of a class
• Inheritance
• DataClass
• This will not be a formal treatment of OOP but to link your knowledge of OOP with python.
What is a class?
• Constructor
• Troubleshoot
• Debug
• Use
• 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}'
• Inheritance is transitive
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
>>> a = Moveable()
TypeError: Can't instantiate abstract class Moveable with abstract methods move
Summary
• Classes may have class variables, methods, as well as instance variables and methods.
• Like javascript and unlike C# you can add and remove attributes (both variables and methods)
dynamically to an object.