eduardo.sufan
eduardo.sufan

Reputation: 165

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? I have understood that a + b is like calling 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'

Upvotes: 0

Views: 135

Answers (1)

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44654

os.path.join() accepts strings, not instances of your custom Path class. You need to access the path attribute of the two objects.

def __add__(self, other):
    return os.path.join(self.path, other.path)

Upvotes: 2

Related Questions