返回信息流用Python2写的domain specific language。但是Python2并不尊重各个Field的顺序:
from __future__ import division, absolute_import, print_function, unicode_literals
class Field(object):
def __init__(self, ty, desc):
self.ty = ty
self.desc = desc
class FieldIntrospectable(type):
def __new__(mcs, name, bases, dict):
for k,v in dict.iteritems():
if isinstance(v, Field):
ty, desc = v.ty, v.desc
print("Field {}: {}\n {}".format(k, ty.__name__, desc))
return type.__new__(mcs, name, bases, dict)
class Student(object):
__metaclass__ = FieldIntrospectable
name = Field(unicode, "The student's name")
score = Field(int, "The score. 100 max")
grade = Field(unicode, "The grade. A, B, C, D or F")
s = Student()
输出结果:
Field grade: unicode
The grade. A, B, C, D or F
Field score: int
The score. 100 max
Field name: unicode
The student's name
但用了Python3之后,metaclass可以在函数体之前运行,创建一个自定义的字典。只要在这个时候把字典替换成collections.OrderedDict,就可以了。
from collections import OrderedDict
class Field(object):
def __init__(self, ty, desc):
self.ty = ty
self.desc = desc
class FieldIntrospectable(type):
@staticmethod
def __prepare__(name, bases, **kwds):
return OrderedDict() # Student类的本体会用这个OrderedDict作为自身的dict
def __new__(mcs, name, bases, dict):
for k,v in dict.items():
if isinstance(v, Field):
ty, desc = v.ty, v.desc
print("Field {}: {}\n {}".format(k, ty.__name__, desc))
return type.__new__(mcs, name, bases, dict)
class Student(metaclass=FieldIntrospectable): # 语法变了。metaclass不再是本体的一部分。
name = Field(str, "The student's name")
score = Field(int, "The score. 100 max")
grade = Field(str, "The grade. A, B, C, D or F")
s = Student()
输出:
Field name: str
The student's name
Field score: int
The score. 100 max
Field grade: str
The grade. A, B, C, D or F
这是一条镜像帖。来源:北邮人论坛 / python / #11752同步于 2016/1/20
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
[metaclass]Py2天地灭,Py3保平安
nuanyangyang
2016/1/20镜像同步27 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
【 在 ztinpn 的大作中提到: 】
: 升级肯定有好处。
: 不过在没触及痛点的时候(并且深切地体会到),大多数人都比较懒吧。[upload=1][/upload]
应该是假设了这些人从Python2学起的。就像现在没有人像下面那样写C程序了:
int foo(a, b)
int a;
char b;
{
...
}
但我觉得新人应该一开始就学Python3,一方面直接避免了很多麻烦(比如字符串和字节串的混淆),另一方面不存在升级的痛苦。
+1
【 在 nuanyangyang (暖羊羊) 的大作中提到: 】
: 应该是假设了这些人从Python2学起的。就像现在没有人像下面那样写C程序了:
: [code=c]
: int foo(a, b)
: ...................
这是什么年代的写法
【 在 nuanyangyang 的大作中提到: 】
:
: 应该是假设了这些人从Python2学起的。就像现在没有人像下面那样写C程序了:
: [code=c]
: ...................
但是遇到问题了,2有大量的参考,3很少啊[ema1]
【 在 nuanyangyang (暖羊羊) 的大作中提到: 】
: 应该是假设了这些人从Python2学起的。就像现在没有人像下面那样写C程序了:
: [code=c]
: int foo(a, b)
: ...................
【 在 wht 的大作中提到: 】
: 但是遇到问题了,2有大量的参考,3很少啊
真的?不是吧,Python的文档一向很全的。看 https://docs.python.org/3/ ,从tutorial、library、language ref到C语言扩展的文档都有。至于第三方的库,各自都有各自的文档。不必发愁没有参考资料。