【问题标题】:Python - Accessing subclasses' variables from parent class while calling classmethodsPython - 在调用类方法时从父类访问子类的变量
【发布时间】:2012-10-28 02:05:09
【问题描述】:

我正在尝试构建一种“迷你 django 模型”,用于在不使用 norel Django 的 dist 的情况下使用 Django 和 MongoDB(我不需要这些的 ORM 访问...)。

所以,我想做的是模仿 django 的默认模型的标准行为或“实现”......这就是我到目前为止所拥有的:

文件“models.py”(基础)

from django.conf import settings
import pymongo

class Model(object):
    @classmethod
    def db(cls):
        db = pymongo.Connection(settings.MONGODB_CONF['host'], settings.MONGODB_CONF['port'])

    @classmethod
    class objects(object):
        @classmethod
        def all(cls):
            db = Model.db() #Not using yet... not even sure if that's the best way to do it
            print Model.collection

文件“mongomodels.py”(实现)

from mongodb import models

class ModelTest1(models.Model):
    database = 'mymongodb'
    collection = 'mymongocollection1'

class ModelTest2(models.Model):
    database = 'mymongodb'
    collection = 'mymongocollection2'

文件“views.py”(视图)

from mongomodels import ModelTest1, ModelTest2

print ModelTest1.objects.all() #Should print 'mymongocollection1'
print ModelTest2.objects.all() #Should print 'mymongocollection2'

问题是它不是从 ModelTest1 访问变量,而是从原始模型访问变量...怎么了??

【问题讨论】:

    标签: python oop class static


    【解决方案1】:

    您必须为objects 提供某种指向包含它的类的链接。目前,您只是对其进行硬编码以使用Model()s 属性。因为您没有实例化这些类,所以您必须使用装饰器或元类在 Model() 的每个子类中为您创建 object 类。

    【讨论】:

    • 实际上我到目前为止所得到的基本上是反复试验的结果,所以我对“装饰器”和“元类”不太熟悉......他们将如何帮助我?我现在正在研究他们……XD
    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 2012-07-04
    • 2023-04-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多