The syntax for using metaclass is different between python2.x and python3.x. On the other hand, you may want to support both versions in one file. How to write in such a case.
metaclass(HasVersion)
There are the following metaclass HasVersionMeta. A metaclass that simply has a string like a version number.
class HasVersionMeta(type):
def __new__(cls, name, bases, attrs):
attrs["version"] = "0.0.1"
return super(HasVersionMeta, cls).__new__(cls, name, bases, attrs)
I want to define a class that uses this.
In the case of python3, add the metaclass option to the argument passed when inheriting.
class A(object, metaclass=HasVersionMeta):
pass
For python2, assign it to a hook with a special name metaclass
class A(object):
__metaclass__ = HasVersionMeta
The class used as a metaclass is also a callable object. Considering that the parent class type () is used when dynamically generating a class, it should have the same function. So you can write as follows.
HasVersion = HasVersionMeta("A", (object, ), {"__doc__": HasVersionMeta.__doc__})
class A(HasVersion):
pass
Operate.
print(A.version)
# 0.0.1
Recommended Posts