# minte9 learningjourney

S R Q

### Attributes

p265 You can assign values to an instance using dot.

# Class attributes ...
#
# Use dot to assign values to a class instance

class Point:
""" a 2D point """

p = Point()
p.x = 1
p.y = 2

assert p.x == 1
assert p.y == 2


### Argument

You can pass an instance as an argument.

# Function arguments ...
#
# Class instances can be pass as arguments to functions

class Point:
""" a 2D point """

p = Point()
p.x = 1
p.y = 2

def print_point(point):
print('(%s, %s)' % (point.x, point.y))

print_point(p) # (1, 2)


### Docstring

The docstring lists the attributes.

# Class definition ...
#
# Use docstring to lists attributes

class Rectangle:
"""Represents a rectangle.
attributes: width, height, corner
"""

class Point:
"""A 2-D point"""
# simple comment (not used by __doc__)

print(Rectangle.__doc__)
# Represents a rectangle.
#     attributes: width, height, corner - Look Here

print(Point.__doc__)
# A 2-D point

box = Rectangle()
box.width = 100
box.height = 200
box.corner = Point() # corner - embeded object
box.corner.x = 10
box.corner.y = 20

assert box.width == 100
assert box.corner.x == 10


### Distance

Distance between two points using a class Point().

# Function distance() ...
#
# Distance between two points ...
# takes 2 Point() objects as argument
# returns the distance between them

import math

class Point: """ a 2D point """

def distance_between_points(p1, p2):
dx = (p2.x - p1.x)**2
dy = (p2.y - p1.y)**2
return math.sqrt(dx + dy)

a = Point()
a.x = 0
a.y = 0

b = Point()
b.x = 3
b.y = 4

assert distance_between_points(a, b) == 5


Questions
Last update: 10 days ago