[] ch.3 - when objects are alike (p79 of 456)
- In the programming world, duplicate code is considered evil. We should not have multiple copies of the same, or similar, code in different places.
[] ch.3 - when objects are alike (p83 of 456)
class Point:
def __init__(self,x,y):
self.move(x,y)
def move(self,x=0,y=0):
self.x = x
self.y = y
def reset(self):
self.move(0,0)
def calculate_distance(self,other_point):
return math.sqrt(
( self.x - other_point.x )**2 +
( self.y - other_point.y )**2
)
point1 = Point(3,5)
print(point1.x,point1.y)
point1.reset()
point1.move(3,4)
print(point1.x,point1.y)
print(point1.calculate_distance(point1))
The global keyword tells Python that the database variable inside initialize_database is the module level one we
just defined. If we had not specified the variable as global, Python would have created a new local variable that
would be discarded when the method exits, leaving the module-level value unchanged. As these two examples
illustrate, all module-level code is executed immediately at the time it is imported. However, if it is inside a
method or function, the function will be created, but its internal code will not be executed until the function
is called. This can be a tricky thing for scripts that perform execution (such as the main script in our e-commerce example). Sometimes, we write a program that does something useful, and then later find that we want to import a
function or class from that module into a different program. However, as soon as we import it, any code at the module level is immediately executed. If we are not careful, we can end up running the first program when we really only
meant to access a couple of functions inside that module.
- and
To solve this, we should always put our start up code in a function (conventionally, called main) and
only execute that function when we know we are running the module as a script, but not when our code
is being imported from a different script. We can do this by guarding the call to main inside a conditional
statement, demonstrated as follow
Python Access Control and OOP