zoukankan      html  css  js  c++  java
  • 面向对象进阶小结

    一、面向对象进阶小结

    1.1 类的继承

    继承父类,则会有父类的所有属性和方法

    class ParentClass1():
    	pass
    	
    class ParentClass2():
    	pass
    
    class SubClass(ParentClass1,ParentClass2):
    	pass
    

    1.2 类的派生

    继承父类的同时自己有init,然后也需要父类的init

    class ParentClass1():
    	def __init__(self,name):
    		pass
    	
    
    class SubClass(ParentClass):
    	def __init__(self,age):
    		# 1. ParentClass1.__init__(self,name)
    		# 2. super(SubClass,self).__init__(name)
    		self.age = age	
    

    1.3 类的组合

    类对象可以引用/当做参数传入/当做返回值/当做容器元素,类似于函数对象

    class ParentClass1():
    	count = 0
    	def __init__(self,name):
    		pass
    
    class SubClass(ParentClass):
    	def __init__(self,age):
    		self.age = age	
    
    pc = ParentClass1()
    sc = SubClass()
    
    sc.parent_class = pc  # 组合
    sc.parent_class.count  # 0
    

    1.4 菱形继承问题

    新式类:继承object的类,python3中全是新式类

    经典类:没有继承object的类,只有python2中有

    在菱形继承的时候,新式类是广度优先(老祖宗最后找);经典类深度优先(一路找到底,再找旁边的)

    1.5 多态与多态性

    一种事物的多种形态,动物-->人/猪/狗

    # 多态
    import abc
    
    class Animal(metaclass=abc.ABCmeta):
    	@abc.abstractmethod
    	def eat():
    		print('eat')
    
    class People(Animal):
    	def eat():
    		pass
    
    class Pig(Animal):
    	def eat():
    		pass
        def run():
            pass
    
    class Dog(Animal):  # 报错
    	def run():
    		pass
    		
    # 多态性
    peo = People()
    peo.eat()
    peo1 = People()
    peo1.eat()
    pig = Pig()
    pig.eat()
    
    def func(obj):
    	obj.eat()
    
    class Cat(Animal):
    	def eat():
    		pass
    cat = Cat()
    
    func(cat)
    

    鸭子类型:只要长得像鸭子,叫的像鸭子,游泳像鸭子,就是鸭子.

    1.6 类的封装

    隐藏属性,只有类内部可以访问,类外部不可以访问

    class Foo():
    	__count = 0 
    	
    	def get_count(self):
    		return self.__count
    		
    f = Foo()
    f.__count  # 报错
    f._Foo__count # 不能这样做
    

    1.7 类的property特性

    把方法变成属性引用

    class People():
    	def __init__(self,height,weight):
    		self.height = height
    		self.weight = weight
    	
    	@property
    	def bmi(self):
    		return weight/(height**2)
    		
    	@bmi.setter
    	def bmi(self,value)
    		print('setter')
            
        @bmi.deleter
        def bmi(self):
            print('delter')
    
    peo = People
    peo.bmi
    

    1.8 类与对象的绑定方法和非绑定方法

    没有任何装饰器装饰的方法就是对象的绑定方法, 类能调用, 但是必须得传参给self

    被 @classmethod 装饰器装饰的方法是类的绑定方法,参数写成cls, cls是类本身, 对象也能调用, 参数cls还是类本身

    被 @staticmethod 装饰器装饰的方法就是非绑定方法, 就是一个普通的函数

  • 相关阅读:
    懒加载 和 json
    [iOS]用instancetype代替id作返回类型有什么好处?
    (转)Objective-C语法之KVC使用
    UITableView 展示数据
    shopee
    防火墙
    vue项目开发技巧
    文件流
    vant
    node 使用
  • 原文地址:https://www.cnblogs.com/nickchen121/p/11070457.html
Copyright © 2011-2022 走看看