相关疑难解决方法(0)

Python:创建类实例而不调用初始化程序

有没有办法避免__init__在初始化时调用类,例如从类方法?

我试图在Python中创建一个案例和标点符号不敏感的字符串类,用于有效的比较目的但是在没有调用的情况下创建新实例时遇到了问题__init__.

>>> class String:

    def __init__(self, string):
        self.__string = tuple(string.split())
        self.__simple = tuple(self.__simple())

    def __simple(self):
        letter = lambda s: ''.join(filter(lambda s: 'a' <= s <= 'z', s))
        return filter(bool, map(letter, map(str.lower, self.__string)))

    def __eq__(self, other):
        assert isinstance(other, String)
        return self.__simple == other.__simple

    def __getitem__(self, key):
        assert isinstance(key, slice)
        string = String()
        string.__string = self.__string[key]
        string.__simple = self.__simple[key]
        return string

    def __iter__(self):
        return iter(self.__string)

>>> String('Hello, world!')[1:]
Traceback (most recent call last):
  File "<pyshell#2>", line 1, …
Run Code Online (Sandbox Code Playgroud)

python constructor initialization class

28
推荐指数
3
解决办法
2万
查看次数

标签 统计

class ×1

constructor ×1

initialization ×1

python ×1