【问题标题】:Can we have a different __name__ attribute for different aliasess of a Python class?我们可以为 Python 类的不同别名设置不同的 __name__ 属性吗?
【发布时间】:2016-10-16 00:10:30
【问题描述】:

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

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”。 有可能吗?怎么样?

【问题讨论】:

    标签: python alias classname


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      相关资源
      最近更新 更多