py16-面向对象介绍与类
面向过程:核心是过程二字,过程指的是问题的解决步骤,即先干什么再干什么,基于面向
过程去设计程序就好比在设计一条流水线,是一种机械式的思维方式
优点:复杂的问题流程化,进而简单化
缺点:可扩展性差
应用:脚本程序,比如linux系统管理脚本,著名案例:linux内核,httpd,git
面向对象:核心是对象二字,对象就是特征与技能的结合体
优点:可扩展性强
缺点:复杂
类:是一系列对象相似的特征与技能的结合体
在现实世界中,先有一个个具体存在的对象,总结相似之处---现实中的类
在程序中:一定是先定义类,后调用类产生对象
定义类:
class OldboyStudent:
school = 'oldboy'
def learn(self):
print('is learning')
print('========>')
#类体的代码在类定义阶段就会执行
查看类的名称空间:
class OldboyStudent:
school = 'oldboy'
def learn(self):
print('is learning')
print(OldboyStudent.__dict__)
再定义:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
print(OldboyStudent.__dict__)
获取类内部的值:
class OldboyStudent:
school = 'oldboy'
def learn(self):
print('is learning')
def eat(self):
print('is eating')
print(OldboyStudent.__dict__['school'])
print(OldboyStudent.__dict__['learn'])
访问类的属性:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
# print(OldboyStudent.__dict__['school'])
# print(OldboyStudent.__dict__['learn'])
print(OldboyStudent.school)
print(OldboyStudent.learn) #就是函数的内存地址加()执行这个函数
类的函数属性的函数调用:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
# print(OldboyStudent.__dict__['school'])
# print(OldboyStudent.__dict__['learn'])
print(OldboyStudent.school)
print(OldboyStudent.learn)
OldboyStudent.learn(123)
修改类的属性:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
# print(OldboyStudent.__dict__['school'])
# print(OldboyStudent.__dict__['learn'])
print(OldboyStudent.school)
print(OldboyStudent.learn)
OldboyStudent.x='xtyang' #添加类的属性
OldboyStudent.school='Oldboy' #修改类的属性
print(OldboyStudent.__dict__) #查看
删除类的属性:
class OldboyStudent:
school = 'oldboy' #类的数据属性
def learn(self): #类的函数属性
print('is learning')
def eat(self):
print('is eating')
# print(OldboyStudent.__dict__['school'])
# print(OldboyStudent.__dict__['learn'])
print(OldboyStudent.school)
print(OldboyStudent.learn)
OldboyStudent.x='xtyang'
OldboyStudent.school='Oldboy'
del OldboyStudent.school #删除类的属性
print(OldboyStudent.__dict__)