Data and procedures that belong to the class
Data attributes
: think of data that make up the class
: ex) coordinate is made up of two numbers
Methods (procedural attributes)
: functions that only work with this class
: how to interact with the object?
: ex) you can define a distance btw. two coordinate objects
The "." operator is used to access any attribute
Format
class Coordinate(object) :
def __init__ (self, x, y) : # special method, initialize some data attributes
self.x = x
self.y = y
: object is class parent. This means that Coordinate is a Python object and inherits (상속, 나중에 배움) all its attributes
: Coordinate is a subclass of object
: object is a superclass ob Coordinate
: self is parameter to refer to an instance of the class
See this code
class Coordinate(object) :
def __init__ (self, x, y) :
self.x = x
self.y = y
c = Coordinate(3, 4)
origin = Coordinate(0, 0)
print(c.x) # 3
print(origin.x) # 0
: Don't provide argument for self, Python does this automatically
: self goes to c
: x goes to 3
: y goes to 4
class Coordinate(object) :
def __init__ (self, x, y) :
self.x = x
self.y = y
def distance(self, other) :
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
: other is another parameter to method (other Coordinate object)
class Coordinate(object) :
def __init__ (self, x, y) :
self.x = x
self.y = y
def distance(self, other) :
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
c = Coordinate(3, 4)
zero = Coordinate(0, 0)
print(c.distance(zero))
class Coordinate(object) :
def __init__ (self, x, y) :
self.x = x
self.y = y
def distance(self, other) :
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
c = Coordinate(3, 4)
zero = Coordinate(0, 0)
print(Coordinate.distance(c, zero))
class Coordinate(object) :
def __init__ (self, x, y) :
self.x = x
self.y = y
def distance(self, other) :
x_diff_sq = (self.x - other.x) ** 2
y_diff_sq = (self.y - other.y) ** 2
return (x_diff_sq + y_diff_sq) ** 0.5
def __str__(self) :
return "<" + str(self.x) + "," + str(self.y) + ">"
c = Coordinate(3, 4)
print(c) # <3,4>
__add__(self, other) -> self + other
__sub__(self, other) -> self - other
__eq__(self, ohter) -> self == other
__lt__(slef, other) -> self < other
__len__(slef) -> len(self)
__str__(self) -> print(self)