I have been trying to create a sample script for inheritance in Python, but I don't know how to make a member variable for a class immutable.
In the following code, I want the symbol of the object to not be able to be changed.
#How to make member variables permanent?
#Customizing class creation 3.4.3
#print '#'+'-'*79
#Tutorial Doctor 5/28/15
#------------------------------------------------------------------------------
#CLASSES
#------------------------------------------------------------------------------
class Human(object):
def __init__(self,name='N/A',age=0):
stages=['null','infant','toddler','?','adolescent','adult']
self.name = name
self.age=age
self.stage=stages[0]
if self.age<=2:
self.stage=stages[1]
elif self.age<=5:
self.stage=stages[2]
elif self.age<18 and self.age >=13:
self.stage=stages[4]
elif self.age>=18:
self.stage=stages[5]
else:
self.stage=stages[3]
class Female(Human):
#This is the init function for the present class
def __init__(self,name='Female',age=0):
#Loading the init function for the inherited class and whichever variables you want to inherit
Human.__init__(self,name,age)
#Adding more variables
self.SYMBOL = 'o+'
class Male(Human):
def __init__(self,name='Male',age=0):
Human.__init__(self,name,age)
self.SYMBOL='o->'
class Woman(Female):
def __init__(self,name='Woman',age=18):
Female.__init__(self,name,age)
class Girl(Female):
def __init__(self,name='Girl',age=0):
Female.__init__(self,name,age)
class Man(Male):
def __init__(self,name='Man',age=18):
Male.__init__(self,name,age)
class Boy(Male):
def __init__(self,name='Boy',age=0):
Male.__init__(self,name,age)
#-------------------------------------------------------------------------------
#INSTANTIATION
#-------------------------------------------------------------------------------
human=Human()
print human.name
print human.age
print
sarah=Woman('Sarah',35)
print sarah.name
print sarah.SYMBOL
print sarah.age
print sarah.stage
print
joey=Man('Joey',17)
print joey.name
print joey.SYMBOL
print joey.age
print joey.stage
billy = Boy('Bill',1)
print billy.stage + " is billy's stage"
jill = Girl('Jill',5)
print jill.stage + " is jill's stage"
#------------------------------------------------------------------------------
#FUNCTIONS
#------------------------------------------------------------------------------
#Returns True if input is a male
def is_male(x):
if x.SYMBOL=='o->':
return True
return False
#Returns True if input is a female
def is_female(x):
if x.SYMBOL=='o+':
return True
return False
print
print is_male(sarah)
print is_male(joey)
print is_female(sarah)
if is_female(sarah):
print sarah.name + ' is old enough.'
#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
print Human.__subclasses__()
print
print sarah.__class__()
print
print dir()
print
print dir(Man)
How would I do this in Python?