一、面向对象编程
(1)面向过程: 通过完成一步一步的步骤从而解决问题的编程思路
(2)面向对象: 视角不再是解决某问题,而是包含了多个问题的系统,这个系统我们称之为对象 函数和变量,在类视角中,就是方法和属性
class Student:
1、类属性 :所有的实例共享的一个属性
count = 0
2、魔法方法:构造函数,当通过类名创建实例时会触发执行的函数
def __init__(self, grade, pro, name):
实例属性:每一个实例都有一套自己的属性
self.grade = grade
self.pro = pro
self.name = name
Student.count += 1
3、实例方法 是每一个实例都拥有的方法,实例方法中可以随意的操作实例属性
def show_info(self):
print(self.grade, self.pro, self.name)
4、类方法:所有实例共享的一个方法,类方法中可以随意操作类属性
@classmethod
def show_count(cls):
print(f"人类的数是:{cls.count}")
5、静态方法:静态方法可以跟类毫无关联,如果开发者想要将该方法写到类中,可以将其声明为静态方法
@staticmethod
def add(a, b):
return a + b
①当判断两个实例是否相等时触发的__eq__函数,判断结果就是__eq__的返回值
def __eq__(self, other):
if self.name == other.name:
return True
else:
return False
②当两个实例之间相加时,触发__add__函数,相加的结果就是__add__的返回值
def __add__(self, other):
return Student(self.name + other.name, self.grade + other.grade, self.pro + other.pro)
③当实例被str()转为字符串时,触发__str__函数,转化的结果就是__str__的返回值
def __str__(self):
s = f"名字:{self.name} 年级{self.grade} 专业:{self.pro}"
return s
s1 = Student(1, "计科", "张三")
s2 = Student(2, "软工", "李四")
s3 = Student(3, "电信", "王五")
s1.show_info()
s2.show_info()
s3.show_info()
Student.show_count()
二、 封装的好处:
(1)提升代码可读性,只暴露一些关键的方法和属性,供人使用,使用者无需关心的方法和属性全部隐藏起来
(2)提升代码的安全性
(3)我们可以通过给被隐藏的属性设置set和get方法来限制调用者的操作
class Human:
def __init__(self, name, age, height):
self.name = name
①私有属性:变量名前面有__就是私有属性,在类的外部无法调用,并且无法被继承
self.__age = age
②受保护的属性:变量名前面有一个_就是受保护的属性,在类外部不建议嗲用,可以被继承
self._height = height
封装的方法1:在各个编程语言中我们都可以给私有或首保护的属性通过get和set设置方法
def get_age(self):
return self.__age
def set_age(self, age):
if type(age) == int:
self.__age = age
else:
print("参数必须是整数")
封装的方法2:使用Property类来创建一个私有或受保护属性的外部代言人
当给age进行赋值时,会自动调用set_age方法。当获取age的数值,会返回get_age的结果。
age = property(get_age,set_age)
封装方法3:使用装饰器@property @xxx.setter
@property
def age(self):
return self.__age
@age.setter
def age(self, age):
if type(age) == int:
self.__age = age
else:
print("参数必须是整数")
h = Human("小张", 60, 183)
h.age = "10"
print(h.age)