Professional Documents
Culture Documents
CP164
CP164
Classes: Object oriented way of thinking bundling data and functionality together
● Creates a new type of object allowing new instances if that class to be made
Ex. Think of movies as a class and “the new instances” as the “GENRES” within the class
Creating Objects:
Two parts are required to create a class:
(1) The name of the class
(2) The class constructor which is always named “__init__”
Example of creating a class:
class Name: (1)(Name of class)
Def __init__(self[,param,]): (2)(Class Constructor)
Note: The constructor must always start with the keyword “def”. All classes must contain at least
1 parameter.
● Class methods MUST be indented within the class to show that they belong to the class
● You can call a class by using the name of the class not the name of the constructor
Importing a class:
● We can import a class by using the following syntax “from module import class”
Note: The keyword “self” is not used as an argument, but is used in order to create the object
method
Class Attributes:
● Class attributes are defined within the class constructor (self is not a class attribute) by
putting the keyword “self” in front of the class attribute
Ex.
Class Number: (1) Name of class
Def __init__(self, value): (class attribute named “value”)
return
This attribution class named “value” can be now used into another Pyhton module and used to
define object:
Ex.
From Number import Number
Example = Number(0)
Using Methods:
● Python doesn’t have a way to make attributes and methods truly private or
inaccessible from outside the class
Print Lists of Objects:
Note: when printing a lists of objects, you must make sure you print each object separately
Ex.
fv = open(“Students.txt”,”r”)
Students = read_students(fv)
fv.close()