python字符串的表示形式_python - 如何为类对象创建自定义字符串表示形式?_class_酷徒编程知识库...
當前python 3的更新如下:class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object, metaclass=MC):
pass
print(C)
如果希望跨python 2和python 3運行的代碼,則six模塊將包含以下內容:from __future__ import print_function
from six import with_metaclass
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(with_metaclass(MC)):
pass
print(C)
最后,如果你有一個想要自定義靜態,的類,基于上面的類的方法很有效,但是如果有幾個,則必須生成類似于MC的類類似于,并且可以使用,from __future__ import print_function
from six import with_metaclass
def custom_class_repr(name):
"""
Factory that returns custom metaclass with a class ``__repr__`` that
returns ``name``.
"""
return type('whatever', (type,), {'__repr__': lambda self: name})
class C(with_metaclass(custom_class_repr('Wahaha!'))): pass
class D(with_metaclass(custom_class_repr('Booyah!'))): pass
class E(with_metaclass(custom_class_repr('Gotcha!'))): pass
print(C, D, E)
打印:Wahaha! Booyah! Gotcha!
元編程并不是你每天都需要的東西,但是當你需要它的時候,它真的很適合你!
總結
以上是生活随笔為你收集整理的python字符串的表示形式_python - 如何为类对象创建自定义字符串表示形式?_class_酷徒编程知识库...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机一级13点,2013年计算机一级考
- 下一篇: 电文的编码和译码c语言实现,电文的编码及