Python 3继承属性错误。如何解决?

2024-04-25 12:50:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了很多关于Python继承的书,但是我不明白如何正确地使用它。我学习了如何使用Java进行继承,所以我想这就是为什么我有点困惑的原因。你知道吗

这是我的超级课堂:

class MongoData:
    def __init__(self, db_name, coll_name):
        self.__config = configparser.ConfigParser()
        self.__config.read('conf.ini')
        self.__connect = self.__config.get('mongo', 'connect')
        self.__client = MongoClient(self.__connect)
        self.__db_name = db_name
        self.__coll_name = coll_name
        self.__db = None
        self.__coll = None

        if self.__db_name in self.__client.database_names(): # If DB already exists
            print('DB exist')
            self.__db = self.__client[self.__db_name]
            if self.__coll_name in self.__db.collection_names(): # If collection already exists
                print('Collection exists')
                self.__coll = self.__db[self.__coll_name]

            else: # If collection does not exist, create it
                self.__db = self.__db_name
                self.__coll = self.__db[self.__coll_name]
                print(self.__db.collection_names())

        else: # If DB does not exist, create it
            print('Creating database...')
            self.__db = self.__client[self.__db_name]
            self.__coll = self.__db[self.__coll_name]
            #print(self.__db.collection_names())
            print("Database {} and collection {} successfully created.".format(self.__db_name, self.__coll_name))

    def writeDB(self, wdict):
        """Method to implement"""
        raise NotImplementedError

如您所见,我有一个大的init,我想在我的子类中继承它。我还有一个抽象方法要在子类中实现。你知道吗

下面是我的子类代码:

class AttackDB(MongoData):
    __metaclass__  = abc.ABCMeta

    def __init__(self, db_name, coll_name):
        MongoData.__init__(self, db_name, coll_name)

    @abc.abstractmethod
    def writeDB(self, wdict):
        doc_id = self.__coll.insert_one(attack).inserted_id
        print("Attack with id {} was inserted in the DB.".format(dic_id))

正如我所想,我得到了一个属性错误

AttributeError: 'AttackDB' object has no attribute '_AttackDB__coll'

我的问题是,我能做些什么来重写这个洞呢?你知道吗

谢谢你。你知道吗

编辑: 在返回self.__dbself.__coll的超类中如何?这对我很有效,但我不确定这是否是一个“好”的解决方案。你知道吗


Tags: nameselfclientidconfigdbifnames
1条回答
网友
1楼 · 发布于 2024-04-25 12:50:42

欢迎来到Python,Elena!你知道吗

正如您已经注意到的,Python在处理继承方面与其他语言有些不同。由于python的特性,您所发现的被称为^{}。你知道吗

所以如果你写:

class MongoData:
    def __init__(self, db_name, coll_name):
        self.__config = configparser.ConfigParser()

在child中得到的是名为_MongoData__config的变量,而不是self.__config(还记得_AttackDB__coll吗?)不过,这可能会让您有点困惑,因为您对Python的工作原理有了更好的了解,事情终于开始有了意义。你知道吗

一种语言的最佳实践并不总是适用于其他语言,因此这里的建议是要么使用不同的命名,要么使用组合而不是继承。即使Mixin模式在某种程度上也可能是危险的。你知道吗

希望这能回答你的问题。你知道吗

相关问题 更多 >