When I was learning the Python Crash Course, one question that is not answered in the book is to use an Instance as Attributes.
Let me show a quick example:
class Car():
def __init__(self, make, model):
self.make = make
self.model = model
self.tank = Tank()
def get_car_info(self):
long_name = self.make + ' ' + self.model
print('The car is', long_name)
class Tank():
def __init__(self, tank_size=20):
self.tank_size = tank_size
def tank_info(self):
print('The tank size is', self.tank_size, 'gallons')
my_car = Car('Audi', 'S4')
my_car.get_car_info()
my_car.tank.tank_info()
>>>
The car is Audi S4
The tank size is 20 gallons
Apparently, I created two classes named Car and Tank, I want to use the Tank class instance as an attribute for the Car. The codes will work out, no problem here.
But what I noticed is that the code that I invoke the Tank method:
my_car.tank.tank_info()
If I understand correctly, the first 'tank' should mean the class 'Tank'. So why should I lowercase it? I tried to upper case, the code won't work.
my_caris an instance ofCar.my_carhas an attribute namedtankwhich was assigned an instance ofTankwhen it was created.my_car.tank. ...is accessingmy_car'stankattribute`.self.tank = Tank()assigned an instance;self.tank = Tankwould have assigned the class itself.