python学习笔记8--类进阶

## __new__方法

#最先调用

#__new__方法 必须返回父类的__new__方法才能继续往后执行

#self 实例本身 cls 类本身

class Person:

    def __init__(self):

        print('实例化的时候用init')

    def __new__(cls, *args, **kwargs):

        print('this is new')

a=Person()

#**用__new__方法实现单例模式

#每一个实例对象 id相同 说明指向了同一片空间

#hasattr 判断类里是否有某属性

class Person:#

    def __new__(cls, *args, **kwargs):

      if not hasattr(cls,'instance'):

          #如果类里无instance 这个instance等于父类的new方法

          cls.instance=super().__new__(cls)

        #返回instance其实就是返回 父类的new方法

      return cls.instance

    def __init__(self,name):

        self.name=name

han=Person('hs')

xiao=Person('xb')

print(han.name)#han与xiao使用同一空间

print(xiao.name)

print(id(han))

print(id(xiao))

## 定制属性访问(增,删,改,查)

class Rectangle:

    def __init__(self,length,width):

        self.length=length

        self.width=width

    def __getattr__(self, item):

        return 111#调用getattr时无该属性返回111

    def Area(self):

      print('%s'%(self.length*self.width))

      return self.length*self.width

a=Rectangle(10,10)

#查  hasattr 返回bool值, getattr 返回具体值

print(hasattr(a,'length'))#返回bool值

print(getattr(a,'length'))#返回具体值

#加  setattr

a.name='hah'

setattr(a,'age',18)

print(getattr(a,'age'))

#修改  setattr

print(getattr(a,'length'))

setattr(a,'length',100)

print(getattr(a,'length'))

#删 delattr

print(hasattr(a,'length'))

delattr(a,'length')

print(hasattr(a,'length'))

## 描述符

#类里一个属性 控制访问该属性如何返回值 做一些额外操作

class Base:

    def __get__(self, instance, owner):

        print('op')

    def __set__(self, instance, value):

        print('cp%s'%value)

    def __delete__(self, instance):

        print('dp')

class A:

    base=Base()#实例化

a=A()

a.base #调用__get__的内容

a.base=20#重新赋值就会使用__set__

del a.base #使用del时 就会调用__delete__

## **装饰器 @

#语法糖,使代码更简洁

#被装饰的函数为f1会当作参数传递给装饰函数(aa)->aa(f1)

#装饰函数在执行完自己后 会把结果给到被装饰函数f1()=aa(f1)()=bb()

def aa(fun):

    print('this is aa')

    def bb():

        if a==1:

            fun()

        else:pass

    return bb

@aa#->f1=aa(f1)=bb

def f1():

    print('thi is f1')

f1(a=1)#在不改变函数(f1)的基础上 增加额外功能

#时间戳 格林威治时间 1970.1.1到现在的总秒数

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容