ME 4990: Intro to CS�Object-Oriented Programming & Machine Learning 101
�
Class!
Outline
A type of thing
A type of thing
A type of thing
* Not strict in Python, but it is a common practice
A type of thing
Define a class
A type of thing
Outline
Modeling
Square
Rectangle
Circle
Modeling
Square:
-length
Rectangle:
-length
-width
Circle:
-radius
Modeling
Square:
-length
Rectangle:
-length
-width
Circle:
-radius
Design Question
Outline
Class “Point”
greenPoint
redPoint
Class “Point”
greenPoint
redPoint
Class declaration
Constructor, must have, do not omit self!
List all attributes with default value is a good habit
Class “Point”
greenPoint
redPoint
Instantiate an instance of a point
Assign values to the instance
Instantiate another instance of a point
Instantiate another instance; this instance uses default attribute values
Class inside a class
Rectangle class
Copying aliasing
Copying
Outline
Class
Method: Introduction
Method
Image from online source
Method
Method Syntax 101: method without argument
Declare a method
Using def
self must be there!
To access the attribute and methods of this class, use self.
objectName.method(), no self needed
Method Syntax 102: method with argument
Declare a method
Using def
self must be there as the first argument
To access the attribute and methods of this class, use self.
newX and newY are arguments of the method (with default), no self on argument of the method
objectName.method()
No self needed. Put arguments here, best practice to list argument names
Your turn
Method in method
Use self.methodName() to call a method within the same class.
No self in the argument. If the method has other arguments, you should pass them here
Outline
Constructor __init__(self)
greenPoint
Constructor __init__(self, args)
__str__(self):
Operator overloading
Practice
Practice
Practice 2