标签:
#!/usr/bin/env python #_*_coding:utf8_*_ class People(object): infor = ‘test info‘#类变量 infor_dic = { "name":‘dodo‘, "age":30 } #字典可以共享,浅copy知识 def __init__(self,name,age,job): #构造方法,实现参数初始化 self.name = name self.__age = age #私有变量,不可外部调用,只可类内部调用,外部不可更改 self.job = job def __breath(self):#私有方法,不可外部调用,只可类内部调用 print(‘{}正在呼吸中.....‘.format(self.name)) def get_age(self,target): if target == ‘age‘: print("age:{}".format(self.__age)) #内部调用私有变量 elif targe == ‘who‘: print(‘None...‘) else: print("hahahahhahahaha") def walk(self): print("{} walking....".format(self.name)) self.__breath()#内部调用私有方法 def talk(self): print("{} talking....".format(self.name)) if __name__ == ‘__main__‘: p1 = People("dodo",23,‘xiguan‘) print(‘p1.name:{}‘.format(p1.name)) #print(‘p1.age:{}‘.format(p1.get_age("age"))) p1.get_age(‘age‘) p1.walk() p1.talk() #p1.__age外部不能访问私有变量,如果实在要访问可为p1._People__age p1._People__age = 30#一般不建议这样访问私有变量 print(‘age‘,p1._People__age) print(‘name‘,p1.name) print(‘job‘,p1.job)
标签:
原文地址:http://www.cnblogs.com/dodoye/p/5515857.html