주장한다. __div__
을 사용하는 방법의 예로서
>>> p = Path('/etc')
>>> q = p/'init.d'/'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
, 여기
str
를 확장하는 간단한 클래스입니다. 적어도 하나의 인수가
MyPath
의 인스턴스 인 경우 작동해야합니다 (즉, 두 개의 일반 문자열에는 작동하지 않음).
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")
수 없습니다. 백 슬래시가 아니라 표준 유형이 아닙니다. 백 슬래시는 파이썬 표현식에서 줄 연속을 나타내는 데 사용됩니다. '/'와 같은 기존 연산자를 사용할 수 있지만 연산자의 동작을 무시하려면 사용자 정의 유형이 필요합니다. –
'os.path.join ('home', 'codes')'은 어떻습니까? – inspectorG4dget
Python 3.4는 새로운 모듈 ['pathlib'] (https://docs.python.org/dev/library/pathlib.html)을 가지고 있습니다. –