5.3 KiB
5.3 KiB
The smell of classes¶
The "data bundle" smell¶
In [ ]:
def momentum(mass, velocity):
return mass * velocity
def energy(mass, velocity):
return 0.5 * mass * velocity ** 2
def update_position(velocity, position, dt):
return position + velocity * dt
In [ ]:
# Naive
mass1 = 10.0
velocity1 = 0.9
mass2 = 12.0
velocity2 = 0.1
print(momentum(mass1, velocity1))
print(momentum(mass2, velocity2))
We have two parameters that will be sent to these functions over and over again: mass
and velocity
.
Moreover, the parameters cannot be mixed up (e.g. the velocity of one particle with the mass of another).
In [ ]:
Introducing classes as a data bundle template¶
In [1]:
class Particle:
pass
In [ ]:
In [ ]:
Class methods¶
In [ ]:
def momentum(particle):
return particle.mass * particle.velocity
print(momentum(particle1))
print(momentum(particle2))
In [ ]:
class Particle:
def __init__(self, mass, velocity):
self.mass = mass
self.velocity = velocity
# Method here
particle1 = Particle(10.0, 0.9, 0.0)
print(particle1.momentum())
In [ ]:
We have been using class instances and methods all along...
In [ ]:
s = 'A scanner Darkly'
s.capitalize()
In [ ]:
x = set(['apple', 'banana', 'apple', 'pineapple'])
x
In [ ]:
x.union(['banana', 'kiwi'])
In [ ]: