【问题标题】:How do I create new methods and attributes for built-in datatypes in python? [duplicate]如何为 python 中的内置数据类型创建新方法和属性? [复制]
【发布时间】:2022-01-16 05:25:42
【问题描述】:

我想为str 数据类型创建新方法。这是我尝试过的

class str(str):
    def __init__(self) -> None:
        super().__init__()

    def work(self):
        # Just for testing
        print("works")

在这里,当我使用 str() 初始化字符串时,这是可行的,但是将它们包裹在简单的引号中会引发错误 AttributeError: 'str' object has no attribute 'work'

像这样:

b = str("Hello world")
b.work()

使用标准输出"works"按预期工作

但是,

a = "Hello world"
a.work()

提高AttributeError: 'str' object has no attribute 'work'

我想创建新方法以便它们适用于这些情况:

"foo".work()
str("foo").work() # <- This actually works :D
bar = "foo"; bar.work()

感谢您的帮助。

【问题讨论】:

  • 我会强烈建议不要这样做。也许创建一个新类Str,它是str的子类,但不要将子类与父类调用相同的东西,因为它只会在阅读代码时导致混乱,你会遇到问题像这样。
  • 这部分是拼写问题吗? self.words 而不是 self.works?
  • Python创建字符串对象的各种方式,比如你的源代码中引用的文字,直接调用str类的C语言实现——名称“str”不查在此过程中,您绝对无法通过 Python 代码来改变这种行为。
  • 不是真的,words 应该在以后使用。我应该编辑帖子以避免混淆。感谢@esramish 的评论。
  • 你真的不能。您是否正在尝试解决一些特定的问题?有多种选择,但最好的选择取决于您想做什么。

标签: python python-3.x string


【解决方案1】:

这是无法做到的,因为str 是 Python 中的不可变类型之一。不可变类型包括boolintfloattuplestringfrozenset,也许还有一些我不知道的。

对于其他类型,您可能可以执行以下操作:

class MyClass:
    def __str__(self):
        return "my class"


def print_me_quoted(self):
    print(f'"{self}"')

mc_old = MyClass()
MyClass.print_me_quoted = print_me_quoted
mc_new = MyClass()

# both now have it
mc_old.print_me_quoted()
mc_new.print_me_quoted()

仍然是一个非常糟糕的主意,像这样通过猴子修补来改变一个类的行为,但它可以做到。希望您的编辑器或 IDE 不喜欢它或不理解它 - 您会看到警告。

如果你用str试试这个:

def print_me_quoted(self):
    print(f'"{self}"')


str.print_me_quoted = print_me_quoted
mc = str(10)
mc.print_me_quoted()

你会得到这个TypeError

TypeError: cannot set 'print_me_quoted' attribute of immutable type 'str'

您可以在自己的str 版本上执行此操作:

class Str(str):
    ...


def print_me_quoted(self):
    print(f'"{self}"')


Str.print_me_quoted = print_me_quoted
mc = Str(10)
mc.print_me_quoted()

但这当然不会改变字符串的标准行为——这正是重点。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2016-02-07
    • 2017-02-20
    • 2021-12-17
    • 2011-03-13
    • 2019-11-29
    • 2012-08-30
    • 2021-02-08
    相关资源
    最近更新 更多