1. instance variables.py
class athlete: def __init__(self): self.event = "Commonwealth Games" mary = athlete() mary.event = "Olympics" print(mary.event)
class athlete: event = "Commonwealth Games" #initialise instances: #all athletes at Commonwealth Games: steve = athlete() joan = athlete() print(steve.event) print(joan.event) #change the __class__ blueprint variable, #which changes all the instances of that class. #Now all athletes at World Championships: athlete.event = "World Championships" print(steve.event) print(joan.event) #Because i'm referring to the instance Steve, #the class variable 'event' for Steve #is now owned by the instance Steve: steve.event = "injured - not competing" #So if i update the athlete class, #Steve's event wont change (unlike Joan's): athlete.event = "Olympics" print(steve.event) #prints "injured - not competing" print(joan.event) #prints "Olympics"
For more information on Python class variable scope check out these Stack Overflow dicussions:
Variables inside and outside of a class
Changing variables in multiple Python instances