#person.py class person: """class to representaion a person""" def __init__(self,name,age): self.name=name if 0<age<=150: self.age=age else: print ‘age is no valid!‘ def display(self): print(‘person(%s,%d)‘%(self.name,self.age)) def __str__(self): return ‘person(%s,%d)‘ %(self.name,self.age) def __repr__(self): return str(self)
>>> p=person(‘hehe‘,30) >>> p.name ‘hehe‘ >>> p.age 30
self.__age=age访问私有变量:
>>>p=person(‘hehe‘,30) >>>p._person__age对象名._类名__私有变量名
Python学习(三):入门篇:Python中怎么编写类,布布扣,bubuko.com
原文:http://blog.csdn.net/jxlijunhao/article/details/24885551