如何访问基类中类的字段?

2024-10-01 22:36:02 发布

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

我有一些类可以访问mongoDB中的集合。我为每个类创建了很多方法。现在我想知道是否有办法实现这些方法一次,然后我的mongoDB类只包含字段?看看这个例子:

#mongoBase.py
class MongoBase():
    def insert()
        pass
    def update()
        pass

#user.py
class User(MongoBase):
# Here should be only fields declaration and when I call .insert(), the fields should be inserted.

我使用Java反射在Java中实现了它。但我在python里找不到这样的东西。你知道吗


Tags: 方法pyfieldsmongodbdefpassbejava
1条回答
网友
1楼 · 发布于 2024-10-01 22:36:02

我很确定只要在父类中引用self,就可以实现您想要做的事情。你知道吗

以下是我使用的代码:

class MongoBase(object):
    def insert(self, field, value):
        setattr(self, field, value)
    def update(self, field, value):
        setattr(self, field, value)

class User(MongoBase):
    def __init__(self, name):
        self.name = name

下面是它的工作原理:

>>> user = User('Bob')
>>> user.name
'Bob'
>>> user.update('name', 'Rob')
>>> user.name
'Rob'
>>> user.insert('age', 12)
>>> user.age
12

相关问题 更多 >

    热门问题