繁体   English   中英

Python:如何使 class 方法与父 class 的实例方法通信

[英]Python: how to make a class method communicate with an instance method of a parent class

从理论上讲,我了解 class 方法和实例方法之间的区别。 现在我有一个实际案例,我尝试利用 class 方法。

基本上我有一个看起来像这样的 mongodb 包装器:

class Model(dict):

    __getattr__ = dict.get
    __delattr__ = dict.__delitem__
    __setattr__ = dict.__setitem__

    def create(self):
        self.collection.insert(self)

这就是我使用它的方式:

class Document(Model):
    collection = mongo.db.My_collection

x = Document({'Name': 'BOB', 'Age': 26})
x.create()

现在,我想利用 class 方法来避免实例化我的对象。 这是我选择的方法:

class Document(Model):
    collection = mongo.db.My_collection

    @classmethod
    def create_item(cls, item):
        cls.create(item)

Document.create_item({'Name': 'BOB', 'Age': 26})

这里我继承自Model class。 然后我创建了一个 class 方法create_item 最后我尝试调用父 class 的create方法,但出现错误:

AttributeError: 'dict' object has no attribute 'collection'

所以我的问题是:

  • 如何使 class 方法与父 class 的实例方法通信?
  • 其次,使用 class 方法实现这些类的最佳策略是什么?

create一个类方法

class Model(dict):
    __getattr__ = dict.get
    __delattr__ = dict.__delitem__
    __setattr__ = dict.__setitem__

    @classmethod
    def create(cls,item):
        #print(cls, cls.collection)
        cls.collection.insert(item)

# MY mongo.db.collection
class F:
    @staticmethod
    def insert(item):
        print(item)

class Document(Model):
    #collection = mongo.db.My_collection
    collection = F()

    @classmethod
    def create_item(cls, item):
        cls.create(item)

>>> Document.create_item({'Name': 'BOB', 'Age': 26})
{'Name': 'BOB', 'Age': 26}
>>>

许多未知数来评论您为什么需要或想要以这种方式构建事物,但这只是我的意见。

似乎create可能是与 class 无关的独立function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM