문제

I would like to implement the concatenation of paths to files using "\" as an operator, redefining the corresponding function (if any).

For example:

path1 = '\home'
path2 = 'codes'

codepath = path1 \ path2

Thus, adding str "\" between path1 and path2 in the redefition of the method, I should assert codepath = '\home\codes'

도움이 되었습니까?

해결책

The pathlib module supports / for concatenating path objects.

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

As an example of how to use __div__, here's a simple class that extends str. It should work as long as at least one argument is an instance of MyPath (i.e., it won't work with two plain strings).

class MyPath(str):
    def __div__(self, other):
        assert isinstance(other, str)
        return os.path.join(self, other)
    def __rdiv__(self, other):
        assert isinstance(other, str)
        return os.path.join(other, self)

# Using __div__
print MyPath("/home/bob") / MyPath("bin")
print MyPath("/home/bob") / "bin"

# Using __rdiv__
print "/home/bob" / MyPath("bin")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top