python note 21 面向对象编程

1、面向对象方式格式

定义:
    class 类名:                    - 定义了一个类                    
        def 函数名(self):        - 在类中编写了一个"方法"
            pass 
调用:
    x1 = 类名()                    - 创建了一个对象/实例化一个对象
    x1.函数名()                    - 通过对象调用其中一个方法.            

 

2、面向对象代码如何编写

class Foo:            
    def __init__(self,name):
      self.name = name 
                    
                    
    def detail(self,msg):
    print(self.name,msg)
                    
obj = Foo()
obj.detail()

 

归类

方式一:归类+提取公共值

归类:
class File:
    def file_read(self, file_path):
        pass

    def file_update(self, file_path):
        pass

    def file_delete(self, file_path):
        pass

    def file_add(self, file_path):
        pass

class Excel:
    def excel_read(self, file_path):
        pass

    def excel_update(self, file_path):
        pass

    def excel_delete(self, file_path):
        pass

    def excel_add(self, file_path):
        pass

提取公共值:
class File:
    def __init__(self, file_path):
        self.file_path = file_path

    def file_read(self):
        pass

    def file_update(self):
        pass

    def file_delete(self):
        pass

    def file_add(self):
        pass

class Excel:
    def __init__(self, file_path):
        self.file_path = file_path

    def excel_read(self):
        pass

    def excel_update(self):
        pass

    def excel_delete(self):
        pass

    def excel_add(self):
        pass

 

方式二:在指定类中编写和当前类相关的所有代码 + 提取公共值

class Message:
    def email(self):
        pass

class Person:
    def __init__(self, na, gen, age, fig)
        self.name = na
        self.gender = gen
        self.age = age
        self.fight = fig

    def grassland(self):
        self.fight = self.fight - 10

    def practice(self):
        self.fight = self.fight + 90

    def incest(self):
        self.fight = self.fight - 666

cang = Person('苍井井', '', 18, 1000)  # 创建苍井井角色
dong = Person('东尼木木', '', 20, 1800)  # 创建东尼木木角色
bo = Person('波多多', '', 19, 2500)  # 创建波多多角色

dong.grassland()

 

3、面向对象的三大特性:封装/继承/多态 

封装

封装:
    将相关功能封装到一个类中:
     class Message:
        def email(self):pass
        def msg(self):pass
        def wechat(self):pass
    将数据封装到一个对象中:
                
    class Person:
        def __init__(self,name,age,gender):
           self.name = name
          self.age = age
          self.gender = gender
                        
    obj = Person('孙福来',18,'')       

继承

支持多继承(先找左/再找右)

继承:
class SuperBase:
    def f3(self):
        print('f3')

class Base(SuperBase):  # 父类,基类
    def f2(self):
        print('f2')

class Foo(Base):  # 子类,派生类
    def f1(self):
        print('f1')

obj = Foo()
obj.f1()
obj.f2()
obj.f3()
# 原则:现在自己类中找,么有就去父类

 

posted @ 2019-06-10 22:01  P-Z-W  阅读(133)  评论(0编辑  收藏  举报