Unit 8
嚜燃nit 8
Classes and Objects; Inheritance
Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Except where otherwise noted, this work is licensed under:
OOP, Defining a Class
? Python was built as a procedural language
每 OOP exists and works fine, but feels a bit more "tacked on"
每 Java probably does classes better than Python (gasp)
? Declaring a class:
class name:
statements
2
Fields
name = value
每 Example:
class Point:
x = 0
y = 0
point.py
1
2
3
class Point:
x = 0
y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
每 can be declared directly inside class (as shown here)
or in constructors (more common)
每 Python does not really have encapsulation or private fields
? relies on caller to "be nice" and not mess with objects' contents
3
Using a Class
import class
每 client programs must import the classes they use
point_main.py
1
2
3
4
5
6
7
8
9
10
from Point import *
# main
p1 = Point()
p1.x = 7
p1.y = -3
...
# Python objects are dynamic (can add fields any time!)
p1.name = "Tyler Durden"
4
Object Methods
def name(self, parameter, ..., parameter):
statements
每 self must be the first parameter to any object method
? represents the "implicit parameter" (this in Java)
每 must access the object's fields through the self reference
class Point:
def translate(self, dx, dy):
self.x += dx
self.y += dy
...
5
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- dictionaries store connections between pieces of list comprehensions a
- i analogy nested loops and tables multiplication table
- multiplying like rabbits university of washington
- cs 125 course notes 1 fall 2016
- python chapter 1 introduction to programming in python 1 1 compiled
- python for economists harvard university
- polynomialmultiplicationandfastfouriertransform isu sites
- spirit python spirit prayer deliverance multiplying freedom
- think python green tea press
- introduction to python harvard university