MIT6 0001F16 Python Classes And Inheritance

2y ago
27 Views
2 Downloads
1.56 MB
26 Pages
Last View : 2m ago
Last Download : 3m ago
Upload by : Ryan Jay
Transcription

PYTHON CLASSESand INHERITANCE(download slides and .py files ĂŶĚ follow along!)6.0001 LECTURE 96.0001 LECTURE 91

LAST TIME abstract data types through classes Coordinate example Fraction exampleTODAY more on classes getters and setters information hiding class variables inheritance6.0001 LECTURE 92

IMPLEMENTINGUSINGTHE CLASSvs THE CLASS write code from two different perspectivesimplementing a newobject type with a classusing the new object type incode define the class define data attributes(WHAT IS the object) define methods(HOW TO use the object)6.0001 LECTURE 9 create instances of theobject type do operations with them3

CLASS DEFINITIONINSTANCEOF AN OBJECT TYPE vs OF A CLASS instance is one specific object class name is the typeclass Coordinate(object)coord Coordinate(1,2) class is defined generically data attribute values varybetween instances use self to refer to someinstance while defining theclassc1 Coordinate(1,2)c2 Coordinate(3,4) (self.x – self.y)**2 self is aparameter tomethods in class definition class defines data andmethods common across allinstancesand c2 have different dataattribute values c1.x and c2.xbecause they are differentobjectsc1 instance has the structure ofthe class6.0001 LECTURE 94

WHY USE OOP ANDCLASSES OF OBJECTS? mimic real life group different objects part of the same typeImage Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CCBY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY6.0001 LECTURE 95

WHY USE OOP ANDCLASSES OF OBJECTS? mimic real life group different objects part of the same typeImage Credits, clockwise from top: Image Courtesy Harald Wehner, in the public Domain. Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CCBY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY6.0001 LECTURE 96

GROUPS OF OBJECTS HAVEATTRIBUTES (RECAP) data attributes how can you represent your object with data?what it isfor a coordinate: x and y valuesfor an animal: age, name procedural attributes (behavior/operations/methods) how can someone interact with the object?what it doesfor a coordinate: find distance between twofor an animal: make a sound6.0001 LECTURE 97

HOW TO DEFINE A CLASS(RECAP)class Animal(object):def init (self, age):self.age ageself.name Nonemyanimal Animal(3)6.0001 LECTURE 98

GETTER AND SETTER METHODSclass Animal(object):def init (self, age):self.age ageself.name Nonedef get age(self):return self.agedef get name(self):return self.namedef set age(self, newage):self.age newagedef set name(self, newname ""):self.name newnamedef str (self):return "animal:" str(self.name) ":" str(self.age) getters and setters should be used outside of class toaccess data attributes6.0001 LECTURE 99

AN INSTANCE andDOT NOTATION (RECAP) instantiation creates an instance of an objecta Animal(3) dot notation used to access attributes (data andmethods) though it is better to use getters and settersto access data attributesa.agea.get age()6.0001 LECTURE 910

INFORMATION HIDING author of class definition may change data attributevariable namesclass Animal(object):def init (self, age):self.years agedef get age(self):return self.years if you are accessing data attributes outside the class andclass definition changes, may get errors outside of class, use getters and setters insteaduse a.get age() NOT a.age good style easy to maintain code prevents bugs6.0001 LECTURE 911

PYTHON NOT GREAT ATINFORMATION HIDING allows you to access data from outside class definitionprint(a.age) allows you to write to data from outside class definitiona.age 'infinite' allows you to create data attributes for an instance fromoutside class definitiona.size "tiny" it’s not good style to do any of these!6.0001 LECTURE 912

DEFAULT ARGUMENTS default arguments for formal parameters are used if noactual argument is givendef set name(self, newname ""):self.name newname default argument used herea Animal(3)a.set name()print(a.get name()) argument passed in is used herea Animal(3)a.set name("fluffy")print(a.get name())6.0001 LECTURE 913

HIERARCHIESImage Credits, clockwise from top: Image Courtesy Deeeep, CC-BY-NC. Image Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana, license CC-BY-NC-SA.Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy Kenny Louie, License CC-BY. CourtesyHarald Wehner, in the public Domain.6.0001 LECTURE 914

HIERARCHIES parent class(superclass)Animal child class(subclass) inherits all dataand behaviors ofparent class add more info add more behavior override behaviorPersonCatRabbitStudent6.0001 LECTURE 915

INHERITANCE:PARENT CLASSclass Animal(object):def init (self, age):self.age ageself.name Nonedef get age(self):return self.agedef get name(self):return self.namedef set age(self, newage):self.age newagedef set name(self, newname ""):self.name newnamedef str (self):return "animal:" str(self.name) ":" str(self.age)6.0001 LECTURE 916

INHERITANCE:SUBCLASSclass Cat(Animal):def speak(self):print("meow")def str (self):return "cat:" str(self.name) ":" str(self.age) add new functionality with speak() instance of type Cat can be called with new methods instance of type Animal throws error if called with Cat’snew method init is not missing, uses the Animal version6.0001 LECTURE 917

WHICH METHOD TO USE? subclass can have methods with same name assuperclass for an instance of a class, look for a method name incurrent class definition if not found, look for method name up the hierarchy(in parent, then grandparent, and so on) use first method up the hierarchy that you found withthat method name6.0001 LECTURE 918

class Person(Animal):def init (self, name, age):Animal. init (self, age)self.set name(name)self.friends []def get friends(self):return self.friendsdef add friend(self, fname):if fname not in self.friends:self.friends.append(fname)def speak(self):print("hello")def age diff(self, other):diff self.age - other.ageprint(abs(diff), "year difference")def str (self):return "person:" str(self.name) ":" str(self.age)6.0001 LECTURE 919

import randomclass Student(Person):def init (self, name, age, major None):Person. init (self, name, age)self.major majordef change major(self, major):self.major majordef speak(self):r random.random()if r 0.25:print("i have homework")elif 0.25 r 0.5:print("i need sleep")elif 0.5 r 0.75:print("i should eat")else:print("i am watching tv")def str (self):return "student:" str(self.name) ":" str(self.age) ":" str(self.major)6.0001 LECTURE 920

CLASS VARIABLES AND THERabbit SUBCLASS class variables and their values are shared between allinstances of a classclass Rabbit(Animal):tag 1def init (self, age, parent1 None, parent2 None):Animal. init (self, age)self.parent1 parent1self.parent2 parent2self.rid Rabbit.tagRabbit.tag 1 tag used to give unique id to each new rabbit instance6.0001 LECTURE 921

Rabbit GETTER METHODSclass Rabbit(Animal):tag 1def init (self, age, parent1 None, parent2 None):Animal. init (self, age)self.parent1 parent1self.parent2 parent2self.rid Rabbit.tagRabbit.tag 1def get rid(self):return str(self.rid).zfill(3)def get parent1(self):return self.parent1def get parent2(self):return self.parent26.0001 LECTURE 922

WORKING WITH YOUR OWNTYPESdef add (self, other):# returning object of same type as this classreturn Rabbit(0, self, other)recall Rabbit’s init (self,age, parent1 None, parent2 None) define operator between two Rabbit instances define what something like this does: r4 r1 r2where r1 and r2 are Rabbit instances r4 is a new Rabbit instance with age 0 r4 has self as one parent and other as the other parent in init , parent1 and parent2 are of type Rabbit6.0001 LECTURE 923

SPECIAL METHOD TOCOMPARE TWO Rabbits decide that two rabbits are equal if they have the same twoparentsdef eq (self, other):parents same self.parent1.rid other.parent1.rid \and self.parent2.rid other.parent2.ridparents opposite self.parent2.rid other.parent1.rid \and self.parent1.rid other.parent2.ridreturn parents same or parents opposite compare ids of parents since ids are unique (due to class var) note you can’t compare objects directly for ex. with self.parent1 other.parent1 this calls the eq method over and over until call it on None andgives an AttributeError when it tries to do None.parent16.0001 LECTURE 924

OBJECT ORIENTEDPROGRAMMING create your own collections of data organize information division of work access information in a consistent manner add layers of complexity like functions, classes are a mechanism fordecomposition and abstraction in programming6.0001 LECTURE 925

MIT OpenCourseWarehttps://ocw.mit.edu6.0001 Introduction to Computer Science and Programming in PythonFall 2016For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms.

CLASS DEFINITION INSTANCE OF AN OBJECT TYPE vs OF A CLASS class name is the type class Coordinate(object) class is defined generically use self to refer to some instance while defining the class (self.x – self.y)**2 selfis a parameter to methods in class definition class defines data

Related Documents:

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

TODAY course info what is computation python basics mathematical operations python variables and types NOTE: slides and code files up before each lecture o highly encourage you to download them before lecture o take notes and run code files when I do o bring computers to answer in-class practice exercises! 6.0001 LECTURE 1 2

PROGRAMMING (OOP) EVERYTHING IN PYTHON IS AN OBJECT (and has a type) can create new objects of some type can manipulate objects can destroy objects explicitly using delor just "forget" about them python system will reclaim destroyed or inaccessible objects -called "garbage collection" 6.0001 LECTURE 8 3

American Revolution has fallen into the condition that overtakes so many of the great . 4 events of the past; it is, as Professor Trevor-Roper has written in another connection, taken for granted: "By our explanations, interpretations, assumptions we gradually make it seem automatic, natural, inevitable; we remove from it the sense of wonder, the unpredictability, and therefore the freshness .