Object-Oriented Programming
Image Credit: http://www.clker.com/clipart-557528.html
The University of 1
Copyright By PowCoder代写 加微信 powcoder
Objects IRL
– DescribetheobjectsthatareonyourdeskinthisPadlet.
– If there are too many objects on your desk, you can upload an
image of your desk.
– Mostdeskswillusuallyhave:
– Thedeskitself(duh!)…
– Acomputer…
– Variousobjectse.g.stacksofpaper?keyboard?mouse?
– Complete these sentences: – Mycomputeris….
– Iuseitto….
The University of 2
Procedural Programming
– Python program is generally a set of instructions that tells the computer what to do.
– Wehavelearnthowtoinstructthecomputertoperformasetofactionsin Python:
– Variables and data types: int, float, str
– Data structures: list, tuples, numpy arrays, sets, dictionary
– Output to terminal – print()
– Inputfromterminal–input(),commandlinearguments
– Control flow statements:
• Selection–if,else,elif
• Repetition–while,for – Code reuse:
The University of 3
Built-in functions – print(), input() Modules – math, random, sys, os, time User-definedmodule–krusty
Recap: String Objects (Week 2)
– Pythonisanobject-orientedprogramminglanguage.
– Everythingyouencountersofarisanobject!
– FirstexposuretoobjectsinWeek2–strobjects: – Manymethods:PythonStringMethods
– str.format()
– str.upper()
– str.lower()
– str.capitalize() – str.strip()
– str.split() – DothisEdLesson.
The University of 4
Recap: String Objects(Week 2) – Observations
– Thestringmethodcallsdonotmodifyitsoriginalstring.
– Methodcallsareinthisformat:object_name.method_name() – my_opinion.lower()
– my_opinion.upper()
– my_opinion.strip(“!”)
– BUT,wedidn’tpassanythingintothemethod,howdoesitdo that?!!
– What is the difference between a function and method? The University of 5
Functions vs Methods
– Functionhasnonotionofexistingdata.Itoperatesoninputs (arguments) and produces outputs (return values).
– Methods are functions operating on objects. A method call will use information within the object to calculate/ manipulate it to produce the desired result.
– The keyword self refer to functions and data within the object when written within a class definition.
– Go to Ed Lesson and complete the questions.
The University of 6
Recap: File Input/Output(Week 9)
– Three steps to read from a file or write to a file:
Create a file object
Perform desired actions by calling the file object methods:
• Read data from file – read(), readline(),
readlines()
• Write data to file – write(), writelines()
Close file:
The University of 7
Recap: File Input/Output(Week 9)
– What is a file object?
– Objectisacollectionofdata(attributes)alongwithfunctions(methods)
that can operate on this data.
– InspectafileobjectinsideVSCodeandobservethevariablewindow.
– Canyouseethemethodsthatyouhaveusedlastweektoread/write from/to a file?
– Howaboutthefileattributes?
The University of 8
Object Oriented Programming
– Object-orientedprogrammingbreakstheprogrammingtask into objects.
– Objectisacollectionofdataalongwithfunctions(methods) that can operate on data.
– Example:
– APersonhasaname,age,height,weightAttributes
– APersoncanwalk,run,jump,talkBehaviour/Functions
The University of 9
Marie and Objects
– Classisablueprinttodefinealogicalgroupingofdataand functions.
– Objectisaninstanceoftheclasswithactualvalues.
– AnotherExample:
– ACarhasabrand,enginecapacity,colourAttributes – A Car can accelerate, decelerateBehaviour/Functions
The University of 10
+
+
Class Definition
– Classdefinitionissimilartofunctiondefinitions.
– Keywordclass
– NamingconventionforclassnameisusuallyinCapWords.
class
# Body of the class
def __init__(self, arguments):
# define or assign object attributes
def instance_method(self, arguments): # body of method
def class_method(arguments):
# body of method
– Python documentation:
– https://docs.python.org/3/tutorial/classes.html#
The University of 11
Class Body
– Special methods (starts and ends with double underscores) – __init__ method
• Also known as the constructor
• Creates an instance of the object
– Instance methods
– Musthaveselfasitsfirstparameter.
– Instancemethodscanfreelyaccesstheobject’sattributes – Accessormethods–setters/getters
• Control modification/retrieval of attributes
• Type and error checking before assigning values
– Class methods (TODO: Lec10b)
– DoNOThaveselfasitsfirstparameter.
– Standalonefunctionsthatdonotdependontheinstance
The University of 12
Example: Defining Person
– Let’s define a class called Person that stores and report the details of a person particularly name, age, status – True(alive)/False(dead) and mood.
+name : str
+status: bool
+mood: str
+Person(self,name,age) +set_name(self, update_name) +get_name(self)
+set_age(self, update_age) +get_age(self) +set_status(self, update_status) +get_status(self) +express_mood(self) +say_name(self)
– Can you spot them in the codes on this Ed Lesson? The University of 13
Object Instantiation
– Run person.py in Ed Lesson and observe the output.
– Anobjectisaninstanceofthedefinedclasswithactualvalues. – Eachobjectisindependentofeachother.
– Example:
+name : str
+status: bool
+mood: str
Person1 : Person
name = ‘ ’
status = True
mood = ‘happy’
Person2 : Person
name = ‘ ’
status = False
The University of 14
Driver Program
– Classdefinitioncanbeinamodule(person.py)andcalled from another module (driver.py)
– Samerulesofimportingmodulesapply: – import person
• Must use dot operator syntax
• Constructorcall:person.Person(‘BillGates’,66) – import person as p
• Must use dot operator syntax
• Constructorcall:p.Person(‘BillGates’,66) – from person import Person
• Does not need to use dot operator syntax.
• Constructorcall:Person(‘BillGates’,66)
The University of 15
Special Method: __str__ and __repr__
– Defaultstringrepresentationreturnedbythesemethodsisthe
memory location of the object.
– We can override these methods to display the details of each object by specifying our own definition for these methods inside the class definition.
– DoPart3andPart4 inEdLesson.
– Can you explain the difference between both special methods?
The University of 16
Summary – Classes and Object
– Class is a blueprint to define a logical grouping of data and functions. – Object is an instance of the class with actual values.
class
def __init__(self, arguments):
# define or assign object attributes
def instance_method(self, arguments): # body of method
def class_method(arguments):
# body of method
object1 =
The University of 17
Summary – Instance Method and Variables
• Must have self as its first parameter.
• Function call syntax: objectName.method_name(args)
• All objects have its own value (unique to each object)
• Defined within body of __init__ or setter method
• Initialize during object instantiation through __init__ or modified through setter method
• Syntax to use variable: objectName.variable
The University of 18
Summary – Procedural vs OOP
– Procedural programming
– Sequentiallistofinstructions
– Problem is decompose into smaller problems – implement as functions which perform operations on supplied data.
– Object-oriented Programming
– Abstractdataandfunctionalityas
Problem is describe as interaction between objects.
The University of 19
Summary – Comparison of Problem Solving
GeoLocation
+latitude : float
+longitude: float
+get_distance(self)
+name : str
+driving_license: bool
+my_car: Vehicle
+get_name(self)
• Get name of driver • Get starting point
• Get destination
Determine the distance driven by a Uber driver on each trip.
• For all pairs of starting point and destination given:
• Calculate distance between starting point and destination
+name : str
+mileage: int
+working: bool
+get_mileage(self)
• Display summary of trips for the day.
• Save to a file for future references.
+driver : Person
+mode: Vehicle
+places: GeoLocation
+get_results(self)
The University of 20
Reading This Week
– Python Official Tutorial: https://docs.python.org/3/tutorial/classes.html#a-first-look-at- classes
– Chapter15,16,17.Downey,A.B.(2015).ThinkPython:How to Think Like a Computer Scientist (2e ed.). O’ , Incorporated.
The University of 21
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com