python基础 四、面向对象

第六章 面向对象

继承,多继承

class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象
        super().__init__()    
        print ('Child')
        
    def bar(self,message):
        super().bar(message)
        print ('Child bar fuction')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')

魔术方法

1、new (最先被调用)

2、init (实例化调用(初始化))

3、add (两字符串相加)

4、str (开发者模式)

5、repr (交互模式)

6、call (让实例可以被调用)

单例模式

节省空间

class Earth(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, 'instance'):
            cls.instance = super().__new__(cls)
        return cls.instance

定制属性访问

即对类的实例进行增删改查

a.bbb = 1 
setattr(a, 'bbb, 2) #有bbb属性就改,没有就增加
a.__setattr__('ccc', 3) #底层的魔法方法,效果同上

delattr(b, 'ccc')
b.__delattr__('ccc')
del b

setattr(b, 'length', 5)
b.__setattr__('length', 5)

hasattr(re, 'length') #判断,返回布尔值
getattr(re, 'length') #判断,返回布尔值
b.__getattribute__('length') #查找,返回属性值

装饰器(decorator)

基础装饰器

def deco(func):
    def inner():
        print('======装饰内容======')
        func()
        print('======装饰内容======')
    return inner
@deco
def func():
    print('被装饰代码')

内置装饰器

class Rectangle: 
    def __init__(self, length, width):   
        self.length = length       
        self.width = width   
    def area(self):        
        areas = self.length * self.width       
        return areas   
@property   # 就像访问属性一样  
def area(self):        
    return self.width * self.length 
@staticmethod   # 静态方法
def func():     # self  在调用的时候会报错    
    print('staticmethod func')   
@classmethod    # 类方法 
def show(cls):      # cls 代表类本身  如果加上self,在调用时就要把实例传入        print(cls) 
    print('show fun')

类装饰器
类也可以做装饰器,但是需要定义 call 方法

class Test_Class:   
    def __init__(self, func):      
        self.func = func    
    def __call__(self):     
        print('类')        
        return self.func
@Test_Class
def fun_test():   
    print('这是个测试函数')

猜你喜欢

转载自www.cnblogs.com/xjl-dwy/p/10411696.html