一、attr属性

1.1getattr属性

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __getattr__(self, item):
        print('执行__getattr__')

f1=Foo(10)
print(f1.y)
print(f1,'y')

f1.aaaa          #调用一个对象不存在的属性时,会自动触发getattr

1.2delattra属性

class Foo:
    x=1
    def __init__(self,y):
        self.y=y
    def __delattr__(self, item):
        print('删除操作__delattr__')

f1=Foo(10)
del f1.y
print(f1.x)
del f1.x     #删除属性时,会触发delattr

1.3setattr属性

class Foo:
    x=1
    def __init__(self,y):
        self.y=y

    def __setattr__(self,key,value):
        print('执行__setattr__')
        self.__dict__[key]=value

f1=Foo(10)
print(f1.__dict__)
f1.z=2                 #设置属性时,会自动触发__setattr__
print(f1.__dict__)

二、包装和授权

2.1包装的概念

包装:python为大家提供了标准数据类型,以及丰富的内置方法,其实在很多场景下我们都需要基于标准数据类型来定制我们自己的数据类型,新增/改写方法,这就用到了我们所学的继承/派生知识(其他的标准类型均可以通过下面的方式进行二次加工)

# 包装(二次加工标准类型)
# 继承 + 派生 的方式实现 定制功能
1、重新定义append方法
2、定制新的功能
class List(list):
    def append(self,object): #append类型必须是字符串
        if type(object) is str:
            print("正在添加[%s]"%object)
            #list.append(self,object)#调用父类方法
            super().append(object)
        else:
            print("必须是字符串类型")
    def show_midlle(self):   #取传入值得中间字符
        mid_index = int(len(self)/2)
        return self[mid_index]
f1 = List("helloworld")
f1.append("SB")
print(f1)
f1.append(2222222)
print(f1.show_midlle())
View Code

相关文章:

  • 2021-09-06
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-23
  • 2021-10-31
  • 2022-12-23
  • 2021-08-16
  • 2022-12-23
相关资源
相似解决方案