2020-03-28

学习笔记之三十七

#1、 父类的私有化属性子类不能直接继承
class Person:
def init(self):
self.name=‘李杰’
self.__age=20
class Student(Person):
def show(self):
print(self.name)
def show1(self):
print(self.__age)

s=Student()
s.show()
#返回值为 : 李杰 ,因为self.name非私有化属性
s.show1()
#返回值为: 报错,因为self.__age 为父类的私有化属性,子类不能直接继承

#2、通过构造函数定义子类的初始化属性时,必须得调用父类的初始化属性,
#3、调用父类的初始化属性方法有三种,如下:
class student2(Person):
def iadd(self,money):
super().init()
# super(Student2,self).init()
# Person.init
self.money=money #这是子类的属性在于父类基础上的补充

#3、私有化属性的两种 赋值和获取方式
#私有化:封装 将类的属性私有化
#因为私有化属性不能直接进行修改,所以set和get方法

方法一

class Salary:
def init(self,age):
self.__age=age
def setAge(self, age):
# 判断
# 是否进行修改

def getAge(self):
   return self.__age
# 因为是获取私有化属性,所以需要返回值

#调用
n=Salary(19)
n.setAge(200) # 进行修改
q=n.getAge() #获取
print(q)

#方法二

class Student4:
def init(self,money):
self.__money=money

@proerty
def age(self):  #先获取
    return self.__money
@age.setter
def age(self,money): #再赋值,改变
    self.__money=money
发布了57 篇原创文章 · 获赞 2 · 访问量 615

猜你喜欢

转载自blog.csdn.net/weixin_46400833/article/details/105160804