Intro To OOP in Python
Intro To OOP in Python
Presentation title 2
Classes vs Instances
Presentation title 3
Classes vs Instances
• A class is a blueprint
• . It doesn’t actually contain any data.
• The Person class specifies that a name and an age are necessary for
defining a person, but it doesn’t contain the name or age of any
specific person.
• an instance is an object that is built from a class and contains real data.
An instance of the Person class is not a blueprint anymore. It’s an
actual person with a name, like Mike, who’s 22 years old.
Presentation title 4
How to Define a Class
class Student:
pass
Presentation title 5
Methods in Classes
• Define a method in a class by including function
definitions within the scope of the class block
• There must be a special first argument self in all
of method definitions which gets bound to the
calling instance
• There is usually a special method called
__init__ in most classes
• We’ll talk about both later…
A simple class def: student
class student:
“““A class representing a
student ”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
Attributes
Attributes
• The non-method data stored by objects are called
attributes
• Data attributes
• Variable owned by a particular instance of a class
• Each instance has its own value for it
• These are the most common kind of attribute
Data Attributes
• Data attributes are created and initialized by an __init__()
method.
• Simply assigning to a name creates the attribute
• Inside the class, refer to data attributes using self
• for example, self.full_name
class teacher:
“A class representing teachers.”
def __init__(self,n):
self.full_name = n
def print_name(self):
print self.full_name
Creating and Deleting Instances
Instantiating Objects
• There is no “new” keyword as in Java.
• Just use the class name with ( ) notation and assign the result to a variable
• __init__ serves as a constructor for the class. Usually does some
initialization work
• The arguments passed to the class name are given to its __init__()
method
• So, the __init__ method for student is passed “Bob” and 21 and the new
class instance is bound to b:
b = student(“Bob”, 21)
Constructor: __init__
• An __init__ method can take any number of arguments.
• Like other functions or methods, the arguments can be defined with
default values, making them optional to the caller.
• https://docs.python.org/3/tutorial/classes.html
• https://realpython.com/python3-object-oriented-programming/
Presentation title 19