简体   繁体   中英

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

Theoretically I understand the difference between a class method and an instance method. Now I have a practical case where I try to take advantage of class methods.

Basically i have a mongodb wrapper that looks like this:

class Model(dict):

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

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

This is how i use it:

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

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

Now, I would like to take advantage of the class methods to avoid instantiating my objects. Here is the approach I chose:

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

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

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

Here I inherit from the Model class. Then I create a class method create_item . Finally I try to call the create method of the parent class, but I get the error:

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

So my questions is:

  • How to make a class method communicate with an instance method of a parent class?
  • Secondarily, what would be the best strategy to implement these classes using class methods?

Make create a classmethod

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}
>>>

To many unknowns to comment on why you need or want to structure things this way but then it would just be my opinion.

Seems like create could be a stand-alone function not associated with a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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