python 当左操作数是字符串时,pathlib.Path如何实现“/”?[重复]

iyzzxitl  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(160)

此问题在此处已有答案

Operator overloading in Python: handling different types and order of parameters [duplicate](2个答案)
昨天就关门了。
我了解__truediv__的工作原理,每个this answer
但在这种情况下:

  1. >>> from pathlib import Path
  2. >>> 'foo' / Path('bar')
  3. PosixPath('foo/bar')

字符串
当然,__truediv__是在str上调用的,因为'foo'/的左操作数,在这种情况下,它如何返回Path

k5hmc34c

k5hmc34c1#

这里有一个玩具路径-称之为ploth。它实现了__rtruediv____truediv__,所以你可以用它来做除法。因为str既不实现__rtruediv__也不实现__truediv__,所以Ploth可以做这件事。(我只是从str派生来获得一个方便的构造函数和__repr__()。)

  1. class Ploth(str):
  2. def __rtruediv__(self, other):
  3. print(f"__rtruediv__({self!r}, {other!r})")
  4. return f"{other!r} / {self!r}"
  5. def __truediv__(self, other):
  6. print(f"__truediv__({self!r}, {other!r})")
  7. return f"{self!r} / {other!r}"
  8. print("plar" / Ploth("ploth"))
  9. print(Ploth("ploth") / "plar")

字符串
这将输出:

  1. __rtruediv__('ploth', 'plar')
  2. 'plar' / 'ploth'
  3. __truediv__('ploth', 'plar')
  4. 'ploth' / 'plar'


来自__rtruediv__上的Python文档:
调用这些方法来实现二进制算术运算(+-*@///%divmod()pow()**<<>>&^|)。只有当左操作数不支持相应的操作并且操作数的类型不同时,才会调用这些函数。

展开查看全部

相关问题