gpt4 book ai didi

python - 具有不同基础的同一模块中的两个同名类?

转载 作者:行者123 更新时间:2023-11-28 20:45:48 25 4
gpt4 key购买 nike

我正在尝试设计一个类结构,其中类的基础在运行时确定。非常感谢 the answer to this question about metaclasses , 它点击了 type 函数可以通过在运行时构造基数元组来做到这一点。太棒了。

现在这开启了一个我不确定自己是否满意的可能性——通过一些操作序列我可以得到等同于:

X  = type('X', (object,), {})
Y = type('Y', (X,), {})
Y2 = type('Y', (object,), {})

我现在有两个具有不同继承结构的类(YY2),但它们共享类名 'Y'

c  =  y.__class__
c2 = y2.__class__

(c,c2) #returns (__main__.Y, __main__.Y)
(c.__bases__,c2.__bases__) #returns ((__main__.X,), (object,))

由此看来,类名只是供人类使用的任意字符串,Python 认为如果我想去混淆自己,我欢迎。

这样对吗?如果允许不同的类共享相同的名称,在 Python 的其他地方是否有陷阱在等着我?

最佳答案

我无法评论您为什么要这样做,但如果您确实需要这种动态行为,或许可以考虑使用 metaclass实现你的目标?

无论如何,如果您想知道使用相同的类名是否会在以后引起问题(我假设您的意思是除了可维护性之外的问题 - 正如其他人所说,这很有可能令人困惑和不必要的复杂),那么不,它不会。

documentation for type()非常清楚参数的用途:

The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute

该描述表明该名称仅用于填充 __name__ 字段。事实证明,它基本上是针对人类的,如图in another answer .

事实上,您甚至不需要使用 type() 来执行此操作 - 您可以使用简单的 class 语句来完成。

class X(object): pass
class Y(object): pass

def create_other_y():
class Y(X): pass
global Y2
Y2 = Y

create_other_y()

(Y, Y2) # => (__main__.Y, __main__.Y)
(Y.__bases__, Y2.__bases__) # => ((object,), (__main__.X,))

关于python - 具有不同基础的同一模块中的两个同名类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com