对于Python类的不同别名,我们是否可以使用不同的\uuuu name \uuuuuuu属性?

2024-04-20 13:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常简单的泛型类,只有关键字参数:

class genObj(object):
    def __init__(self, **kwargs):
        for kwa in kwargs:
            self.__setattr__(kwa, kwargs[kwa])

现在,我想对具有不同参数的不同对象使用它,使用别名,如下所示:

rectangle = genObj
rr = rectangle(width=3, height=1)

circle = genObj
cc = circle(radius=2)

工作正常。没问题。我想让类知道它使用了什么别名。现在如果我问:

rr.__class__.__name__
>> "genObj"

cc.__class__.__name__
>> "genObj"

我想得到的是rr查询的“rect”,cc查询的“circle”。 有可能吗?怎么做


Tags: nameself参数objectdefrr关键字kwargs
1条回答
网友
1楼 · 发布于 2024-04-20 13:58:18

问题是,按照您的设置方式,circlerectangle是同一个对象(在本例中是同一类型),所以circle.__name__ is rectangle.__name__。要得到你想要的东西,最干净的方法是使circlerectangle都是genObj的子类。你可以这样做:

class genBase(object):
    def __init__(self, **kwargs):
        for kwa in kwargs:
            self.__setattr__(kwa, kwargs[kwa])

def genObj(name):
    return type(name, (genBase,), {})

circle = genObj("circle")
print issubclass(circle, genBase)
# True
c = circle(r=2)
print type(c).__name__
# circle

相关问题 更多 >