[英]python pathlib operator '/' - how does it do it?
I found the pathlib syntax - or is it the Python syntax - surprising.我发现 pathlib 语法 - 或者它是 Python 语法 - 令人惊讶。 I'd like to know how this makes the forward slash
/
act as a joiner of WindowsPath
s etc. Does it override/overload /
?我想知道这如何使正斜杠
/
充当WindowsPath
等的连接器。它是否覆盖/重载/
? It seems to be in a magical context, the slash is between a WindowsPath
type object and a string.它似乎在一个神奇的上下文中,斜杠位于
WindowsPath
类型 object 和字符串之间。 If I try between 2 strings it fails to join the 2 strings (eg "123" / "123"
fails)如果我在 2 个字符串之间尝试,它无法连接 2 个字符串(例如
"123" / "123"
失败)
p=pathlib.Path(".")
p
Out[66]: WindowsPath('.')
p.cwd()
Out[67]: WindowsPath('C:/Users/user1')
p.cwd() / "mydir"
Out[68]: WindowsPath('C:/Users/user1/mydir')
The Path class has a __truediv__
method that returns another Path. Path类有一个
__truediv__
方法,它返回另一个Path。 You can do the same with your own classes: 您可以对自己的类执行相同的操作:
>>> class WeirdThing(object):
def __truediv__(self, other):
return 'Division!'
>>> WeirdThing() / WeirdThing()
'Division!'
For whoever wants to see the source code briefly:对于任何想简要查看源代码的人:
__truediv__
overload the /
operator, and returns self
, which is a Path
object. __truediv__
重载/
运算符,并返回self
,这是一个Path
object。
# this is where the magic begins! (overload the '/' operator)
def __truediv__(self, key):
try:
return self._make_child((key,))
except TypeError:
return NotImplemented
def _make_child(self, args):
drv, root, parts = self._parse_args(args)
drv, root, parts = self._flavour.join_parsed_parts(
self._drv, self._root, self._parts, drv, root, parts)
return self._from_parsed_parts(drv, root, parts)
@classmethod
def _from_parsed_parts(cls, drv, root, parts):
self = object.__new__(cls)
self._drv = drv
self._root = root
self._parts = parts
return self # finally return 'self', which is a Path object.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.