5

在本质上处理自定义枚举类型实现时,我遇到了一种情况,似乎我必须从两者派生出单独但几乎相同的子类intlong因为它们在 Python 中是不同的类。这似乎有点讽刺意味,因为两者的实例通常可以互换使用,因为在大多数情况下,它们只是在需要时自动创建。

我所拥有的工作正常,但本着 DRY(不要重复自己)的精神,我不禁想知道是否有更好的,或者至少更简洁的方法来实现这一点。目标是让子类实例可以在任何地方使用——或者尽可能接近——它们的基类实例本来可以使用。理想情况下,这应该自动发生,类似于内置在检测到需要时int()实际返回 a的方式。long

这是我当前的实现:

class NamedInt(int):
    """Subclass of type int with a name attribute"""
    __slots__ = "_name"  # also prevents additional attributes from being added

    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError(
                "'NamedInt' object attribute %r is read-only" % name)
        else:
            raise AttributeError(
                "Cannot add attribute %r to 'NamedInt' object" % name)

    def __new__(cls, name, value):
        self = super(NamedInt, NamedInt).__new__(cls, value)
        # avoid call to this subclass's __setattr__
        super(NamedInt, self).__setattr__('_name', name)
        return self

    def __str__(self):  # override string conversion to be name
        return self._name

    __repr__ = __str__


class NamedLong(long):
    """Subclass of type long with a name attribute"""
    # note: subtypes of variable length 'long' type can't have __slots__

    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError(
                "NamedLong object attribute %r is read-only" % name)
        else:
            raise AttributeError(
                "Cannot add attribute %r to 'NamedLong' object" % name)

    def __new__(cls, name, value):
        self = super(NamedLong, NamedLong).__new__(cls, value)
        # avoid call to subclass's __setattr__
        super(NamedLong, self).__setattr__('_name', name)
        return self

    def __str__(self):
        return self._name  # override string conversion to be name

    __repr__ = __str__

class NamedWholeNumber(object):
    """Factory class which creates either a NamedInt or NamedLong
    instance depending on magnitude of its numeric value.
    Basically does the same thing as the built-in int() function
    does but also assigns a '_name' attribute to the numeric value"""
    class __metaclass__(type):
        """NamedWholeNumber metaclass to allocate and initialize the
           appropriate immutable numeric type."""
        def __call__(cls, name, value, base=None):
            """Construct appropriate Named* subclass."""
            # note the int() call may return a long (it will also convert
            # values given in a string along with optional base argument)
            number = int(value) if base is None else int(value, base)

            # determine the type of named numeric subclass to use
            if -sys.maxint-1 <= number <= sys.maxint:
                named_number_class = NamedInt
            else:
                named_number_class = NamedLong

            # return instance of proper named number class
            return named_number_class(name, number)
4

3 回答 3

2

覆盖分配器将使您返回适当类型的对象。

class NamedInt(int):
  def __new__(...):
    if should_be_NamedLong(...):
      return NamedLong(...)
     ...
于 2012-10-19T16:27:52.750 回答
2

以下是通过多重继承解决 DRY 问题的方法。不幸的是,它不能很好地处理__slots__(它会导致 compile-time TypeError)所以我不得不把它排除在外。希望这些__dict__值不会为您的用例浪费太多内存。

class Named(object):
    """Named object mix-in. Not useable directly."""
    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError(
                "%r object attribute %r is read-only" %
                (self.__class__.__name__, name))
        else:
            raise AttributeError(
                "Cannot add attribute %r to %r object" %
                (name, self.__class__.__name__))

    def __new__(cls, name, *args):
        self = super(Named, cls).__new__(cls, *args)
        super(Named, self).__setattr__('_name', name)
        return self

    def __str__(self):  # override string conversion to be name
        return self._name

    __repr__ = __str__

class NamedInt(Named, int):
    """NamedInt class. Constructor will return a NamedLong if value is big."""
    def __new__(cls, name, *args):
        value = int(*args) # will raise an exception on invalid arguments
        if isinstance(value, int):
            return super(NamedInt, cls).__new__(cls, name, value)
        elif isinstance(value, long):
            return NamedLong(name, value)

class NamedLong(Named, long):
    """Nothing to see here."""
    pass
于 2012-10-19T17:41:29.387 回答
2

这是一个类装饰器版本:

def named_number(Named):

    @staticmethod
    def __new__(cls, name, value, base=None):
        value = int(value) if base is None else int(value, base)
        if isinstance(value, int):
            NamedNumber = Named  # NamedInt / NamedLong
        else:
            NamedNumber = cls = NamedLong
        self = super(NamedNumber, cls).__new__(cls, value)
        super(NamedNumber, self).__setattr__('_name', name)
        return self

    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError(
                "'%r' object attribute %r is read-only" % (Named, name))
        else:
            raise AttributeError(
                "Cannot add attribute %r to '%r' object" % (name, Named))

    def __repr__(self):
        return self._name

    __str__ = __repr__

    for k, v in locals().items():
        if k != 'Named':
            setattr(Named, k, v)

    return Named

@named_number
class NamedInt(int):
    __slots__ = '_name'

@named_number
class NamedLong(long): pass
于 2012-10-19T19:28:05.337 回答