-
-
Save NKID00/51021e03c8f979df5bf4cb5adca64cc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Meta(type): | |
def __new__(self, class_name, bases, attrs): | |
print(attrs) | |
return type(class_name, bases, attrs) | |
# 没有更高层级的类且与 Meta 处于同一模块时 Dog1 与 Dog2 等价 | |
Dog1 = Meta('Dog', (), {'x': 5}) | |
class Dog(metaclass=Meta): | |
x = 5 | |
Dog2 = Dog | |
# 存在更高层级的类时 Dog3 与 Dog4 不等价 | |
class Toplevel: | |
Dog3 = Meta('Dog', (), {'x': 5}) | |
class Dog(metaclass=Meta): | |
x = 5 | |
Dog3, Dog4 = Toplevel.Dog3, Topleve2.Dog | |
# __qualname__ 属性(限定名称)不相等 | |
assert(Dog3.__qualname__ == 'Dog') | |
assert(Dog4.__qualname__ == 'Toplevel.Dog') | |
assert(Dog3.__qualname__ != Dog4.__qualname__) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 另一个模块(文件) | |
from .meta_class import Meta | |
# 与 Meta 所处模块不同时 Dog5 与 Dog6 不等价 | |
Dog5 = Meta('Dog', (), {'x': 5}) | |
class Dog(metaclass=Meta): | |
x = 5 | |
Dog6 = Dog | |
# __module__ 属性(所属模块的名称)不相等 | |
assert(Dog5.__module__ == 'meta_class') | |
assert(Dog6.__module__ == 'other_class') | |
assert(Dog5.__module__ != Dog6.__module__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment