我们可以为Python类的不同别名使用不同的__name__属性吗?

时间:2016-06-15 04:05:15

标签: python alias classname

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

GMSMutablePath *path = [GMSMutablePath path];
[path addCoordinate:CLLocationCoordinate2DMake(-33.85, 151.20)];
[path addCoordinate:CLLocationCoordinate2DMake(-33.70, 151.40)];
[path addCoordinate:CLLocationCoordinate2DMake(-33.73, 151.41)];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];

现在我想使用不同的参数,使用别名如下所示:

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查询获取“rect”,为cc查询获取“circle”。 有可能吗?怎么样?

1 个答案:

答案 0 :(得分:1)

问题在于您设置的方式,circlerectangle是同一个对象(在这种情况下是相同的类型),因此circle.__name__ is rectangle.__name__。获得imo的最简洁方法是使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
相关问题