一、封装
二、@property装饰器
三、get、set方法
四、继承
方法重写
一、封装
私有属性和私有方法
1.通常两个下划线开头的属性是私有属性(private),其他为公有(public)
2.类的内部可以访问私有属性
3.类的外部通过“_类名__私有属性(方法)”访问私有属性(方法)
class Person:
def __init__(self,name,age):
self.__name=name
self.__age=age
def __work(self):
print("努力工作赚钱")
p1=Person("小明",18)
print(p1.name)
print(p1.age)
p1.work()
在类的外部访问私有属性和私有方法报错
AttributeError: 'Person' object has no attribute 'name'
进行修改
class Person:
def __init__(self,name,age):
self.__name=name
self.__age=age
def __work(self):
print("努力工作赚钱")
p1=Person("小明",18)
print(p1._Person__name)
print(p1._Person__age)
p1._Person__work()
小明
18
努力工作赚钱
二、@property装饰器
1.@property装饰器可以将一个方法的调用方式变成“属性调用”,不能设置属性
class Person1:
def age(self):
return 18
p1=Person1()
print(p1.age())
class Person2:
@property
def age(self):
return 19
p2=Person2()
print(p2.age)
18
19
三、get和set方法与@property装饰器
录入薪水例子
没有应用@property装饰器之前
class Employee:
def __init__(self,name,salary):
self.__name=name
self.__salary=salary
def get_salary(self):
return self.__salary
def set_salary(self,salary):
if 1000<salary<40000:
self.__salary=salary
else:
print("录入错误,薪水应在1000——40000之间")
e1=Employee("小明",8000)
print(e1.get_salary())
e1.set_salary(9000)
print(e1.get_salary())
8000
9000
应用@property装饰器之后
class Employee:
def __init__(self,name,salary):
self.__name=name
self.__salary=salary
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self,salary):
if 1000<salary<40000:
self.__salary=salary
else:
print("录入错误,薪水应在1000——40000之间")
e1=Employee("小明",8000)
print(e1.salary)
e1.salary=-9000
print(e1.salary)
8000
录入错误,薪水应在1000——40000之间
8000
定义get方法前加@property装饰器,调用时类名.属性,不用加()
定义set方法前加@属性名.setter装饰器,调用时类名.属性=新的值
四、继承
1.Python支持多继承,语法格式为:
class 子类类名(父类1[,父类2,父类3......]):
类体
2.定义子类时,必须在其构造函数中调用父类的构造函数,格式:
父类名.__init__(self,参数列表)
class Person:
def __init__(self,name,age):
self.name=name
self.__age=age #父类的私有属性
def say_age(self):
print("我今年19岁")
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score=score
s=Student("小明",19,100)
s.say_age()
print(s.name)
print(s._Person__age) #利用私有属性调用方法
我今年19岁
小明
19
方法重写
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def say_name(self):
print("我的名字是{0}".format(self.name))
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score=score
def say_name(self): #重写了父类的方法,对父类方法进行覆盖
print("报告老师,我的名字是{0}".format(self.name))
p=Person("小红",18)
p.say_name()
s=Student("小明",19,100)
s.say_name()
我的名字是小红
报告老师,我的名字是小明
通过类的方法mro()可以输出这个类的继承层次
class A: pass class B(A): pass class C(B): pass print(C.mro())结果
[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]