Variable Scope
instance variables.py
class athlete:
def __init__(self):
self.event = "Commonwealth Games"
mary = athlete()
mary.event = "Olympics"
print(mary.event)
class variables.py
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"
- construct a class called "Student" that has a self.property named "Name", that stores the name of the student (e.g. Storme or Kirra).
- in your student class, add a class variable called student number.
- create two new students - Kirra and Storme. each time, increase the class variable student number by one.
For more information on Python class variable scope check out these Stack Overflow dicussions:
Variables inside and outside of a class __init__() function
Changing variables in multiple Python instances