Python面向对象之封装
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python面向对象之封装相关的知识,希望对你有一定的参考价值。
类class
继承(单继承、多继承)
类方法@classmethod修饰
实例方法def fn(self)
静态方法@staticmethod修饰
代码区:
class people: # 定义基本属性 name=‘‘; age=0; # 定义私有属性,类的外部无法访问 __weight=0; def __init__(self, n, a, w): self.name = n; self.age=a; self.weight=w; def speak(self): print(‘%s is %s years old.‘%(self.name, self.age)); p = people(‘dog‘, ‘8‘); p.speak(); class people: # 共有变量 name=‘jack‘; age=12; p = people(); # 直接访问共有变量 print(p.name); print(p.age); class people2: #私有变量 __name=‘jack‘; __age=12; p2 = people2(); # 私有变量外部不可访问 print(p2.name); # 访问会报错 # 通过内部方法访问私有属性 class people: __name=‘jack‘; __age=12; def getName(self): return self.__name; def getAge(self): return self.__age; p = people(); print(p.getName(), p.getAge()); # 实例属性可以不定义在class里 class people: age=12; p = people(); p.name = ‘jack‘; print(p.name, p.age); print(people.age); print(people.name); # 会报错 # 内置的构造方法定义属性 class people: name=‘jack‘; def __init__(self, age): self.age = age; p = people(12); print(p.age); print(people.age); # 会报错 class people: country=‘china‘; print(people.country); # china people.country = ‘Japan‘; print(people.country); # Japan p = people(); print(p.country); # Japan del p.country; # 删除实例属性 print(p.country); # 会报错 class people: country=‘china‘; # 类方法,用classmethod来修饰 @classmethod def getCountry(cls): return cls.country; p = people(); print(p.getCountry()); # china class people: country=‘china‘; # 实例方法 def getCountry(self): return self.country; # 实例化类 p = people(); print(p.getCountry()); # 静态方法 class people: country=‘china‘; # 静态方法 # 静态方法不用传self参数 @staticmethod def getCountry(): # 直接用类名调用变量 return people.country; # 不用实例化即可直接打印静态方法 print(people.getCountry());
以上是关于Python面向对象之封装的主要内容,如果未能解决你的问题,请参考以下文章