【问题标题】:Python generic type wrapperPython 泛型类型包装器
【发布时间】:2020-07-27 22:28:31
【问题描述】:

我假设这个问题已经被问了一百万次了,但我似乎无法理解一些事情,所以请在这里耐心等待。我正在尝试在 Python 中进行通用继承。这就是我想要完成的:我有一个接受泛型类型的方法,它返回一个从该父类继承的类

这就是代码的样子

def make_foo(parent):
    class Relationship(parent):
        # def __init__(self):

        @staticmethod
        def should_see_this_method(self):
            print("Hello here")
            return True

    return Relationship

现在这是我拥有的一段代码

NewType = make_relationship(str)
another_test: NewType = "Hello"
another_test.should_see_this_method()
another_test.capitalize()

现在我收到AttributeError: 'str' object has no attribute 'should_see_this_method'

我不确定这是否是反模式,但我只是好奇知道如何做到这一点。

谢谢

【问题讨论】:

    标签: python


    【解决方案1】:

    这一行:

    another_test: NewType = "Hello"
    

    没有按照你的想法去做。

    这是一个类型提示。静态类型检查器、linter 等使用提示来检查您的代码是否有明显的错误或使用不正确。它可以帮助您在“编译时”捕获可能的错误来源,但它对代码的运行时行为没有影响。

    重要的是,它不构造 NewType 类型的对象。它构造了一个str。您可以通过调用type(another_test) 轻松看到这一点,这表明这是一个str。 (这也在您问题中AttributeError 的消息中。)

    要实际构造该对象,您必须做通常的事情:

    >>> another_test = NewType("Hello")
    >>> isinstance(another_test, NewType)
    True
    

    您的代码中有一个不相关的问题:staticmethods 不应将self 作为第一个参数。它们不受任何实例的约束。一旦你真正到达调用该方法的那一行,你就会看到一个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2012-05-11
      • 2013-04-09
      • 2021-10-06
      相关资源
      最近更新 更多