[Level 2] Python variable scope.
If you want to have a private property in Python class,
you can add an prefix '__' before your variable.
e.g.
in ./lib/libcomm.py
in ./test.py
result:
common instance has no attribute '__age'
24
1
1
10
Wish this helps.
regards,
Stanley Huang
you can add an prefix '__' before your variable.
e.g.
in ./lib/libcomm.py
class common:
def __init__(self, name='stanley', age=25):
self.__name = name
self.__age = age
def setName(self, name):
self.__name = name
def getName(self):
return self.__name
def setAge(self, age):
self.__age = age
def getAge(self):
return self.__age
self.__name = name
self.__age = age
def setName(self, name):
self.__name = name
def getName(self):
return self.__name
def setAge(self, age):
self.__age = age
def getAge(self):
return self.__age
in ./test.py
from lib.libcommon import *
if __name__ == '__main__':
c = common('stanley', 24)
try:
print c.__age
except Exception, e:
print e
print c.getAge()
c.__age = 1
print c.__age
c.setAge(10)
print c.__age
print c.getAge()
c = common('stanley', 24)
try:
print c.__age
except Exception, e:
print e
print c.getAge()
c.__age = 1
print c.__age
c.setAge(10)
print c.__age
print c.getAge()
result:
common instance has no attribute '__age'
24
1
1
10
Wish this helps.
regards,
Stanley Huang
Comments
Post a Comment