先声明一下 各位大佬,这是我的笔记。 如有错误,恳请指正。 另外,感谢您的观看,谢谢啦!
面向对象 :将数据与函数绑定在一起,进行封装,减少重复代码的重写过程
面向过程 : 根据业务逻辑编程
类:一种抽象概念,类别,由多个具有类似属性的对象定义的。
对象:具体存在,属于类,属性是它的描述,方法是它的行为
这样肯定解释肯定不清晰,举几个例子就好了,
类:游戏,汽车,鱼
对象:lol,保时捷帕拉梅拉,小丑鱼
num1,str1,str2是这个类的属性
fc1,fc2是这个类的方法
__init__()会在函数实例化(q = Test())时__自动运行__
该函数常常用来初始化一些属性,和在实例化时就给一些属性赋值
class Student(): def __init__(self,english,math,chinese): self.str1 = '英语' self.num_e = english self.str2 = '数学' self.num_m = math self.str3 = '语文' self.chinese = chinese def print_grade(self): print(f'该学生的成绩为{self.str1}{self.num_e}\t{self.str2}{self.num_m}\t{self.str3}{self.chinese}\t') q = Student(90,89,79) q.print_grade() 该学生的成绩为英语90 数学89 语文79关于这个魔法方法还有一点要注意
在init方法内的属性,外部是可以在已经实例化的情况下直接访问的
而在其他方法内的属性就要先访问这个方法,才能再访问相应的属性
class Student(): def __init__(self,english,math,chinese): self.str1 = '英语' self.num_e = english self.str2 = '数学' self.num_m = math self.str3 = '语文' self.chinese = chinese def print_grade(self): self.num2 = 3 print(f'该学生的成绩为{self.str1}{self.num_e}\t{self.str2}{self.num_m}\t{self.str3}{self.chinese}\t') q = Student(90,89,79) print(q.chinese) print(q.num2) q.print_grade() AttributeError: 'Student' object has no attribute 'num2' 改成这样 print(q.chinese) q.print_grade() print(q.num2) 79 该学生的成绩为英语90 数学89 语文79 3还有一点要注意:init内部__不可以用return语句__
在正常调用对象变量时,打印值为一个地址,可是我不想让他显示一个地址,这时候就可以用__str__()
它的作用是当对象变量被访问时返回一个字符串,注意一定是字符串。
class Student(): def __init__(self,english,math,chinese): self.str1 = '英语' self.num_e = english self.str2 = '数学' self.num_m = math self.str3 = '语文' self.chinese = chinese def print_grade(self): self.num2 = 3 print(f'该学生的成绩为{self.str1}{self.num_e}\t{self.str2}{self.num_m}\t{self.str3}{self.chinese}\t') def __str__(self): return '你成功返回我了' q = Student(90,89,79) print(q) 你成功返回我了不过它还有以下两种形式
def __str__(self): return str(self.chinese) q = Student(90,89,79) print(q) def __str__(self): return self.chinese q = Student(90,89,79) print(q.__str__())结果都是79
有些属性和方法我们不希望直接被访问到,我们可以在它的名字前加上__把他变成私有
class test(): def __init__(self): self.__str1 = '隐私' q = test() print(q.str1) AttributeError: 'test' object has no attribute 'str1'换成这句也是访问不了
print(q.__str1) AttributeError: 'test' object has no attribute '__str1'哪这个值就无法访问了吗?其实不是,在外部我无法访问你,哪我就在内部访问你
class test(): def __init__(self): self.__str1 = '隐私' def disclose(self): print(f'不,你没有{self.__str1}') q = test() q.disclose() 不,你没有隐私而私有函数也是一样的方法
class test(): def __init__(self): self.str1 = '1' def __underclosed(self): print('--1--') q = test() q.underclosed()del 要销毁的对象
fc1 = text() del fc1一定要加上self.别问我怎末知道的