p = Point(x,y)
The constructor Every time the constructor is used, a new instance is spawned
p.x()
The accessor (returns the x value)
p.move(x,y)
The mutator
self._x
is an actual variable, but it uses an object argument. Thus, if the argument is Point, the variable will be Point._x. The self argument is always replaced by the Object on which the method is called.
#Syntax Notes
##Naming Conventions
_underscore means private CAPITALS means constant CapitalizingTheFirstLetter means class underscores_between means generic method
##Loops - Use a for loop when you know how many times it needs to be looped (use range()) - Use a while loop when you don’t know when the loop should terminate. The loop should be terminated by inside conditions.
When the method instance.method(arg1, …) is called, the method defined in Class is used. However, the overridden method can still be accessed directly by calling SuperClass.method(instance, arg1, …)
Every method in a class needs a self tag, because it knows that it needs to be referencing itself, thus bounding it to the class. The self declaration is pulled when the method is attatched like so ClassInstance.method(). The self slot pulls the ClassInstance. That’s why super().init(args) [where the args can be pulled from a top level class initialization] works. It’s initializing things not on its parent class, but its superclass. Like so:
where the top level is
def __init__(self, x):self.x = x
class C(B):def __init__(self, x, y):super().__init__(x)
class ClassName(object):"""docstring for ClassName"""def __init__(self, arg):super().__init__()self.arg = arg
is allowed
Therefore, the super().init(3) line in C’s init method results in calling A.init(3). A’s init will, therefore, set the value of the attribute x to 3. The next line in C.init will now run, setting the value of the attribute y to 5.
import mathepsilon = 1e-5class Point(object):def __init__(self, x, y):self._x = xself._y = ydef __repr__(self):return 'Point({}, {})'.format(self._x, self._y)def dist_to_point(self, other):deltax = self._x - other._x #is this cheating?deltay = self._y - other._yreturn math.sqrt(deltax ** 2 + deltay ** 2)def is_near(self, other):if self.dist_to_point(other) < epsilon:return Trueelse:return Falsedef add_point(self, other):self._x += other._xself._y += other._y