Python
/
Class
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Class Attributes
Assign values to an instance using dot class Point: # a 2D point p = Point() p.x = 1Objects
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