zoukankan      html  css  js  c++  java
  • Python基础28类-内置函数(__getattribute__,__getitem__,__setitem__.__delittem__)

    #__getattribute__
    class Foo:
        def __init__(self,x):
            self.x=x
        def __getattr__(self, item):
            print('执行__getattr__')
        def __getattribute__(self, item):
            print('执行__getattribute__')
            # 当两个方法都存在时,执行__getattribute__()方法,如果__getattribute__方法抛出异常,则执行__getattr__
            raise AttributeError('抛出异常了')
    
    f1=Foo(10)
    f1.xxxx
    
    class Test():
        def __getitem__(self, item):
            print('getitem',item)
            return self.__dict__
    
        def __setitem__(self, key, value):
            print('setitem')
            self.__dict__[key]=value
    
        def __delitem__(self, key):
            print('delitem')
            self.__dict__.pop(key)
    #如果是这种类似字典的格式调用实例,则会调用类上面的内置方法
    t1=Test()
    t1['name']='alex'
    del t1['name']
    print(t1['name'])
    
    #__str__跟__repr__这两个函数返回值必须是字符串,否则报错
    class Test2():
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def __str__(self): #print或str 会调用该函数
            return '名字是%s,年龄是%d' %(self.name,self.age)
        def __repr__(self): #该方法只在编译器中,输入例子中的t2按回车则执行该函数,如果__str__没有定义,则不在编译器中,str或者print函数也会执行该函数
            return '只有名字,是%s' % (self.name, self.age)
    
    t2=Test2('alex',18)
    print(t2)
  • 相关阅读:
    JSP error: Only a type can be imported
    关于JAVA插入Mysql数据库中文乱码问题解决方案
    MySQL SQL优化——分片搜索
    myeclipse 调试JSP页面
    jsp:usebean 常用注意事项
    spring XML格式
    VB 要求对象
    VB 对象变量或with块变量未设置
    Spring依赖注入
    Spring 读取XML配置文件的两种方式
  • 原文地址:https://www.cnblogs.com/josie930813/p/10482072.html
Copyright © 2011-2022 走看看