zoukankan      html  css  js  c++  java
  • 2019年8月11日 类的内置attr 函数

    类本质也是个对象

    class BlackMedium:
        feture='ugly'
        def __init__(self,name1,addr):
            self.name=name1
            self.addr=addr
    
        def sell_hourse(self):
            print('%s正在卖房'%self.name)
    
        def rent_hourse(self):
            print('%s租房子'%self.name)
    
    print(hasattr(BlackMedium,'sell_hourse'))#类本质也是对象,所以也能用attr方法

    》》》

    True

    len(str)-->str.__len__()


    class Foo:
        x=1
        def __init__(self,y):
            self.y=y
    
        def __getattr__(self, item):#调用一个不存在的属性时会触发
            print('调用一个不存在的属性时会触发,执行__getattr__')
    
        def __delattr__(self, item):
            print('删除一个属性时(无论类中是否存在)会触发,执行__delattr__')
           # self.__dict__.pop(item) #底层设置
    
        def __setattr__(self, key, value):
            print('设置属性时候会触发执行__setattr__')
            # self.key=value#设置属性,如果这么设置会进入无限递归,因为init中有设置
            self.__dict__[key]=value#本质是在操作字典,底层字典进行设置,这样不会进入递归
    
    f1=Foo(10)
    print(f1.y)
    
    print(getattr(f1,'y')) #eg:
    
    f1.sss
    del f1.w
    f1.z=2
    print(f1.__dict__)
    print(dir(Foo))
    #dir方法反馈的内置功能最全,从中得知上述3个下划线方法都内置有,
    #只不过通过重新def定义改变了原本定义的功能,由此可知对内置函数进行操作,必须对底层进行操作才不会报错





  • 相关阅读:
    常用软件整理列表
    红黑树的旋转(C语言)
    Linux 内核编译
    2017年9月11日
    2017年 9月10日
    2017年9月8号 开学第一天
    开始学习.net的第二天
    前端工作需要什么
    Kubernetes容器编排技术---Kubernetes基本概念和术语(一)
    监控工具之---Prometheus探索PromQL(二)
  • 原文地址:https://www.cnblogs.com/python1988/p/11336543.html
Copyright © 2011-2022 走看看