封装:
#在属性前加两个’_'表示该属性不希望在类外部被访问 可以通过在类里面创建对应的实例方法进行访问
class Student:
name = '陌言'
__age = 20
place = 'Putian'
def __init__(self):
pass
def name_change(self,name):
self.name = name
def age_change(self,age):
self.__age=age
def place_change(self,place):
self.place = place
def get_age(self):
return self.__age
def inf(self):
print(f'Name:{self.name}; Age:{self.age}; Place:{self.place}')
stu=Student()
print(stu.name)
print(stu._Student__age)
print(stu.get_age())
结果:
陌言 20 20
’ ’ ’ 继承:
class Person:
def __init__(self,name,age):
self.__name=name
self.__age=age
def inf(self):
print(f'name:{self.__name},age:{self.__age}')
class Student(Person):
def __init__(self,name,age,no):
super().__init__(name,age)
self.__no=no
stu=Student('陌言',20,111111)
stu.inf()
name:陌言,age:20
‘ ’ Python是可以多继承的
class A:
pass
class B:
pass
class C(A,B):
pass
‘ ’ 方法重写
class Student(Person):
def __init__(self,name,age,no):
super().__init__(name,age)
self.__no=no
def inf(self):
super().inf()
print(self.__no)
stu=Student('陌言',20,111111)
stu.inf()
name:陌言,age:20 111111
‘ ‘ ’
class Teacher:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return f'name:{self.name},age:{self.age}'
ter=Teacher('陌言',20)
print(ter)
print(ter.__str__())
name:陌言,age:20 name:陌言,age:20
‘ ‘ ’ 多态:
class Animal():
def voice(self):
print('动物会叫')
class Dog(Animal):
def voice(self):
print('WangWang!')
class Cat(Animal):
def voice(self):
print('Miao Miao!')
class Person:
def voice(self):
print('诶嘿?')
def fun(obj):
obj.voice()
fun(Cat())
fun(Dog())
fun(Person())
结果:
Miao Miao! WangWang! 诶嘿?
|