记录一下学习Python3菜鸟教程过程中的笔记。
#类的方法
class people:
name = ''
age = 0
_weight = 0
def __init__(self,n,a,w):
#_init_()是类的一个特殊方法(构造方法),该方法在类实例化时会自动调用。
#类的方法与普通的函数只有一个特别的区别:必须有一个额外的第一个参数名称,按照惯例是self,self代表的是类的实例,代表当前对象的地址,而self.class指向类
self.name = n
self.age = a
self._weight = w
def speak(self):
print("%s 说:我 %d 岁。"%(self.name,self.age))
#类的继承
class student(people):
grade = 0
def __init__(self,n,a,w,g):
#调用父类的构函
people.__init__(self,n,a,w)
self.grade = g
#覆写父类方法
def speak(self):
print("%s 说:我 %d 岁了,读 %d 年级"%(self.name,self.age,self.grade))
#多继承
class speaker():
name = ''
topic = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print("我是 %s,今天演讲的主题是 %s"%(self.name,self.topic))
class sample(speaker,student):
#从左向右查找父类中的方法
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
#类的私有属性和私有方法
#两个下划线开头,只能在类的内部使用
class JustCouter:
__secreCount = 0
publicCount = 0
def count(self):
self.__secreCount += 1
self.publicCount +=1
print(self.__secreCount)
counter = JustCouter()
couter.count()
print(counter.__secreCount) 此时会报错AttributeError: ‘JustCounter’ object has no attribute '__secretCount