1234
3.14159
'Hello'
[1, 5, 7, 19]
{'CA':'California', 'TX':'Texas'}
Structured Programming:
Objects have both data and methods
Objects send and receive messages to invoke actions
Objects of the same class have the same data elements and methods
Key idea in object-oriented programming:
The real world can be accurately described as a collection of objects that interact.
class ClassName:
<statement 1>
<statement 2>
.
.
.
class Point:
"""
Point class represents and
manipulates x,y coords.
"""
pass
p = Point()
type(p)
Python Classes can contain functions, termed methods.
The first example of a method we'll see is __init__.
__init__ allows us to add variables to a class as follows:
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x # The self argument to method represents the
# object, and allows you to assign stuff to the object
self.y = y
p = Point(10, 12)
class Point:
"""
Attributes:
x: float, the x-coordinate of a point
y: float, the y-coordinate of a point
"""
def __init__(self,x,y):
self.x = x
self.y = y
p = Point(10, 12)
print(p.x, p.y)
p.x = 5
p.y = 11
print(p.x, p.y)
class Point:
""" Create a new Point, at coordinates x, y """
def __init__(self, x=0, y=0):
""" Create a new point at x, y """
self.x = x
self.y = y
# We see the "self" argument again
def distance_from_origin(self):
""" Compute my distance from the origin """
# This is just Pythagorus's theorem
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
p = Point(3, 4)
print(p.distance_from_origin())
p = Point(3, 4)
q = Point() # Make a second point
print(p.x, p.y, q.x, q.y)
# Each point object (p and q) has its own x and y
class Point:
# Class variables are defined outside of __init__ and are shared
# by all objects of the class
theta = 10
""" Create a new Point, at coordinates x, y """
def __init__(self, x=0, y=0):
""" Create a new point at x, y """
self.x = x
self.y = y
p = Point(3, 4)
q = Point(9, 10)
print("Before", p.theta, q.theta)
Point.theta = 20 # There is only one theta, so we just
# changed theta value for all Point objects -note the use of the class name
print("After", p.theta, q.theta, Point.theta)
p = Point(5, 10)
p.x += 5 # You can directly modify variables
# You can even add new variables to an object
p.new_variable = 1
print(p.new_variable)
# But note, this doesn't add a "new_variable" to other points
# you might have or create
q = Point(5, 10)
q.new_variable # This doesn't exist,
# because you only added "new_variable" to q
class Point:
""" Create a new Point, at coordinates x, y """
def __init__(self, x=0, y=0):
""" Create a new point at x, y """
self.x = x
self.y = y
def move(self, deltaX, deltaY):
""" Moves coordinates of point
( this is a modifier method, which you call to
change x and y)
"""
self.x += deltaX
self.y += deltaY
p = Point()
p.move(5, 10)
print(p.x, p.y)