簡體   English   中英

如何在python中__add__路徑?

[英]how to __add__ paths in python?

我有以下課程:

# -*- 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)

我需要添加附加有兩條路徑:路徑(“/家庭/”)+路徑('佩佩)

我有兩個問題:

1)如何在方法add中訪問要添加的兩個對象的值? 我知道a + b就像調用a.add(b)...

2)在此代碼中,返回以下錯誤:文件“/home/esufan/anaconda/lib/python2.7/posixpath.py”,第75行,在連接中,如果b.startswith('/'):AttributeError:' Path'對象沒有'startswith'屬性

os.path.join()接受字符串,而不是自定義Path類的實例。 您需要訪問兩個對象的path屬性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM