Python 如何在构造函数之前声明静态变量,如何在类的主体中引用类?

Python 如何在构造函数之前声明静态变量,如何在类的主体中引用类?,python,oop,class,Python,Oop,Class,我习惯于在构造函数之前声明类中的静态字段/变量。在Python中这样做会导致错误 下面是一个示例类: class StringCompare: methods = OrderedDict() # ERROR!: #methods['equals'] = equals #methods['ends with'] = endswith #methods['starts with'] = startswith #methods['contains']

我习惯于在构造函数之前声明类中的静态字段/变量。在Python中这样做会导致错误

下面是一个示例类:

class StringCompare:

    methods = OrderedDict()
    # ERROR!:
    #methods['equals'] = equals
    #methods['ends with'] = endswith
    #methods['starts with'] = startswith
    #methods['contains'] = contains

    @staticmethod
    def equals(a, b):
        return a == b

    @staticmethod
    def contains(a, b):
        return a.find(b) != -1

    @staticmethod
    def startswith(a, b):
        return a.startswith(b)

    @staticmethod
    def endswith(a, b):
        return a.endswith(b)

    methods['equals'] = equals
    methods['ends with'] = endswith
    methods['starts with'] = startswith
    methods['contains'] = contains
有没有更优雅的方法(除了将所有语句直接放在整个类后面,用
StringCompare.
为每个访问的var加上前缀之外)

这里的最佳实践是什么


更复杂的情况是,尝试从同一类中调用构造函数时:

class Type(InlineFragment):

    # primitive types get None as package name
    def __init__(self, packageName, name, genericType=None):

        ...

    def ...

    primitive = {
        'Character': Type(None, 'char'),
        'Byte'     : Type(None, 'byte'),
        'Short'    : Type(None, 'short'),
        'Integer'  : Type(None, 'int'),
        'Long'     : Type(None, 'long'),
        'Boolean'  : Type(None, 'boolean'),
        'Float'    : Type(None, 'float'),
        'Double'   : Type(None, 'double'),
    }
这将导致一个错误:

\jpa_export_fragments.py", line 361, in Type
    'Character'    : Type(None, 'char'),
NameError: name 'Type' is not defined

这应该是可行的,但我只能通过将此代码放在类之外来解决这个问题。

通常,解决方案是使用。对于您的示例,您可能希望将它们与类方法结合使用:

def apply_method(attr):
    def apply_to(cls):
        setattr(cls, attr, getattr(cls, '_' + attr)())
        return cls
    return apply_to

@apply_method('primative')
class Type(object):

    def __init__(self, *args):
        pass

    @classmethod
    def _primative(cls):
        return {
    'Character': cls(None, 'char'),
    'Byte'     : cls(None, 'byte'),
    'Short'    : cls(None, 'short'),
    'Integer'  : cls(None, 'int'),
    'Long'     : cls(None, 'long'),
    'Boolean'  : cls(None, 'boolean'),
    'Float'    : cls(None, 'float'),
    'Double'   : cls(None, 'double'),
        }
您的第一个示例看起来非常不符合python,因此我不太愿意为此推荐一个装饰师。相反,也许您想要一个
str
ing子类

class StringCompare(str):
    # none of these are any different from the normal string operations
    # you would really only override ones that are different.

    def __eq__(self, other):
        return super(StringCompare, self).__eq__(other)

    def __contains__(self, other):
        return self.find(other) != -1

    def startswith(self, other):
        return super(StringCompare, self).startswith(other)

    def endswith(self, other):
        return super(StringCompare, self).endswith(other)


print StringCompare('boogaloo').startswith('boo') # True

虽然我试图提供有用的示例,但答案确实是“Python是不同的,学习它独特的风格。”在Python中,并非所有内容都必须在一个类中
primatives
可能是遵循
类型定义的模块级变量。