zoukankan      html  css  js  c++  java
  • Python __getattr__与__setattr__使用方法

        __getattr__和__setattr__可以用来对属性的设置和取值进行自定义处理,__str__则是字符串形式输出的时候进行自定义处理,

    给出测试用例:

     1 class Book(object):
     
    2     def __setattr__(self,name,value):
     
    3         if name == 'value':
     
    4             object.__setattr__(self,name,value-100)
     
    5         else:
     
    6             object.__setattr__(self,name,value)
     
    7 
     
    8     def __getattribute__(self,name):
     
    9         try:
    10             return object.__getattribute__(self,name)
    11         except:
    12             return name + "is not found"
    13 
    14     def __str__(self):
    15         return self.name + "cost:" + str(self.value)
    16 
    17 c=Book()
    18 c.name='xiaoxia'
    19 c.value = 200
    20 print c.name
    21 print c
    22 print c.value
    23 print c.Type
    24 
    25 输出结果:
    26 xiaoxia
    27 xiaoxiacost:100
    28 100
    29 Typeis not found   


    作者:xiaoxia

    出处:http://cnblogs.com/xiaoxia

    我的淘宝:http://shop62115161.taobao.com/

    本文遵从GNU 的自由文档许可证(Free Document License)的条款,欢迎转载、修改、散布。

  • 相关阅读:
    「CF1027」
    「CF1000G Two-Paths」
    「CF1009」
    「CF1008」
    Vi的按键(常用)
    【codeforces】Codeforces Round #643 (Div. 2)
    【codeforces】Codeforces Round #641 (Div. 2)
    【codeforces】 Codeforces Round #640 (Div. 4)
    【codeforces】Codeforces Round #642 (Div. 3)
    【codeforces】CF1345C Hilbert's Hotel
  • 原文地址:https://www.cnblogs.com/xiaoxia/p/1789090.html
Copyright © 2011-2022 走看看