访问限制
class Dog_dog():
def init(self, name) -> None:
self.__name = name # 定义私有属性
def run(self):
print('我跑的很快!我的名字是', self.__name)
dog1 = Dog_dog(‘papi’)
dog1.run()
print(dog1._Dog_dog__name) # 加入类名访问
print(’-----分界线-----’)
print(dog1.__name)#不能通过对象调用私有属性
私有属性只会在内部被操作的属性。同私有属性一样,在类Bood中定义私有方法__sprak(),通过对象直接调用出错
class Bood():
def __speak(self, sound): # 定义私有方法
print(sound)
def run(self):
self.__speak('汪汪汪')
bood1 = Bood()
bood1.run()
print(’-----分界线-----’)
bood1.__speak()
#错误的调用方法
面向对象编程
封装
class Dog:
def init(self, name, age) -> None:
self.name = name
self.__age = age
def run(self):
print('{0},跑的很快'.format(self.name))
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
dog1 = Dog(‘小芳’, 2)
print(‘我今年{1}岁了,我叫{0}’.format(dog1.name, dog1.get_age())) # 通过get()方法获取年龄
dog1.set_age(5)
通过set()赋值
print(‘修改过后的年龄是{0}’.format(dog1.get_age()))
方法2
class Doog:
def init(self, name, age) -> None:
self.name = name
self.__age = age
def run(self):
print('{0}跑的很快.'.format(self.name))
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
self.__age = age
doog1 = Doog(‘papi’, 3)
print(‘我叫{0},我今年{1}岁’.format(doog1.name, doog1.age))
doog1.age = 6
print(‘修改后的年龄是{0}’.format(doog1.age))
继承
‘’’
class ClassName(baseclasslist):
statement
baseclasslist要继承的父类,可以有多个用逗号隔开
statement类体
‘’’
class Anlin:
def init(self, name) -> None:
self.name = name
def featu(self):
return '小动物是{0}'.format(self.name)
def move(self):
print('移动方式')
class Pig(Anlin):
pass
pig1 = Pig(‘papi’)
pig1.move()
print(pig1.featu())
方法2
class Animal:
def init(self, name) -> None:
self.name = name
def feature(self):
return '小动物是{0}'.format(self.name)
def mo(self):
print('移动方式')
class Unlint(Animal):
def init(self) -> None:
super(Unlint, self).init(‘PP’)
unlint1 = Unlint()
unlint1.mo()
print(’-----分界线-----’)
print(unlint1.feature())
方法3
class Animals:
def init(self, name) -> None:
self.name = name
def features(self):
return '小动物是{0}'.format(self.name)
def mos(self):
print('移动方式')
class Unlints(Animals):
def init(self):
print(‘我是papi’)
Unlints1 = Unlints()
Unlints1.mos()
print(’----分界线----’)
print(Unlints1.features())#调用会出错
方法4
class Horse:
def init(self, name) -> None:
self.name = name
def fature(self):
return '父亲-----马的名字: {0}'.format(self.name)
def mover(self):
print('马儿跑起来很潇洒')
class Monkey:
def init(self, name) -> None:
self.name = name
def fature(self):
return '父类-----驴的名字{0}'.format(self.name)
def speak(self):
print('驴跑的很欢快')
class Mule(Horse, Monkey):
def init(self, name, age) -> None:
super().init(name)
self.age = age
mule1 = Mule(‘朵儿’, 2)
mule1.mover() # 继承父类horse的move()方法
mule1.speak() # 继承父类donkey的speak()方法
print(mule1.fature()) # 继承父类horse的fature()方法
总代码如下:
谢谢观看,制作不易,不喜勿喷
如果喜欢,请点赞加关注哟
小白们,可以照着敲一遍哈