返回顶部

收藏

python魔幻方法:__str__ , __repr__

更多
class adder:
     def __init__(self, value=0):
         self.data = value                  # initialize data
     def __add__(self, other):
         self.data += other                 # add other in-place

class addrepr(adder):                      # inherit __init__, __add__
     def __repr__(self):                    # add string representation
         return 'addrepr(%s)' % self.data   # convert to string as code

class addstr(adder):            
     def __str__(self):                     # __str__ but no __repr__
         return '[Value: %s]' % self.data   # convert to nice string

x = addstr(3)
x + 1
print x                                    # runs __str__

print str(x), repr(x)

标签:Python,Class

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2015-03-23 16:00:44python构造函数 by wubai
  2. 2015-04-12 12:23:16Demonstrates class attributes and static methods by Solon.Ring
  3. 2015-03-25 09:01:36输出对象属性 by wubai
  4. 2015-04-04 09:20:00Print out class tree by 大猪
  5. 2015-05-04 09:28:31python对象声明 by wubai
  6. 2015-04-04 09:41:16python面向对象:__del__函数使用 by jack.chen
  7. 2015-04-13 09:39:34重写内置的__str__方法 by wubai
  8. 2015-04-27 09:21:44python类的成员变量定义 by 西国の海妖
  9. 2015-05-05 14:53:44python自定义list by 阮小七
  10. 2015-05-09 17:34:43Python定义类 by Solon.Ring
  11. 2018-08-21 11:54:27java代码判断数字是否是2的n次方 by 甄码农

发表评论