[英]how to __add__ paths in python?
I have the followong class: 我有以下课程:
# -*- coding: utf-8 -*-
import os
class Path(object):
"Docstring"
@classmethod
def __init__(self, path = ''):
"docstring __init__"
self.path=os.path.normpath(path)
def __eq__(self, ruta):
if self.path == ruta:
return True
else:
return False
def __add__(self, other):
return os.path.join(self, other)
I need to add two paths with add : Path('/home/') + Path('pepe') 我需要添加附加有两条路径:路径(“/家庭/”)+路径('佩佩)
I have 2 problems: 我有两个问题:
1) How do I access the values of both objects to add in the method add ? 1)如何在方法add中访问要添加的两个对象的值? I have understood that a + b is like calling a.add (b) ...
我知道a + b就像调用a.add(b)...
2) in this code, returns me the following error: File "/home/esufan/anaconda/lib/python2.7/posixpath.py", line 75, in join if b.startswith('/'): AttributeError: 'Path' object has no attribute 'startswith' 2)在此代码中,返回以下错误:文件“/home/esufan/anaconda/lib/python2.7/posixpath.py”,第75行,在连接中,如果b.startswith('/'):AttributeError:' Path'对象没有'startswith'属性
os.path.join()
accepts strings, not instances of your custom Path
class. os.path.join()
接受字符串,而不是自定义Path
类的实例。 You need to access the path
attribute of the two objects. 您需要访问两个对象的
path
属性。
def __add__(self, other):
return os.path.join(self.path, other.path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.