面向对象

面向对象  

定义 :class 类名: --定义一个类

def  函数名(self):--在类中写方法

x1=类名()--创建一个对象/实例化对象

x1.函数名()--掉用函数的方法

a.将数据封装到对象里以便调用

 1 class File:
 2     def __init__(self,file_path):
 3         self.file_path=file_path
 4         self.f=open(self.file_path,'r')
 5 
 6     def first_read(self):
 7             pass
 8     def second_read(self):
 9             pass
10     def end_read(self):
11             pass
12 obj=File('C:/xx/xx.log')
13 obj.first_read()
14 obj.end_read()
15 obj.second_read()
16         

b.将数据封装到对象,以便其他函数使用

 1 def func(arg):
 2     arg.k1
 3     arg.k2
 4     arg.k6
 5 class File:
 6     def __init__(self,k1,k2,k6):
 7         self.k1=k1
 8         self.k2=k2
 9         self.k6=k6
10 obj=File(11,22,66)
11 func(obj)
12 
13         
14     

1.规则

 1             class Foo:
 2                 
 3                 def __init__(self,name):
 4                     self.name = name 
 5                     
 6                     
 7                 def detail(self,msg):
 8                     print(self.name,msg)
 9                     
10             obj = Foo()
11             obj.detail()

2.什么时候写

1.归类+提取关键之

2.类相关功能+提取公共值

面向对象三大特征:

封装

1.将相关功能加到一个类中

1 class Message:#当需要分到一类
2     def email(self):pass
3     def msg(self):pass
4     def wechat(self):pass
5         

2.将数据封装到一个对象中:

1 class Person:
2     def __init__(self,name,age,gender):
3         self.name=name
4         self.age=age
5         self.gender=gender
6     def user(self):
7         print('我是%s,我今年%s,我性别%s' % (self.name,self.age,self.gender))

继承

1 class Base:   #父类/基类
2     def f2(self):
3         print('f2')
4 class Foo(Base): #子类/派生类
5     def f1(self):
6         print('f1')

原则:先自己再找,没有找父类 ,优先级按从左到右

obj 是哪一个类,就执行什么方法,就从类开始找

为什么要用继承?

提高代码复用率

原文地址:https://www.cnblogs.com/zhangqing979797/p/9543743.html