如何定义类内有值的变量以及如何在其他类中使用

2024-05-16 06:42:04 发布

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

我在课外有课。类的适当函数需要变量。如何在类内移动它并在其他类中使用它?你知道吗

这很好,但我需要在类UserDevice内移动STATUS_CHOICES,并在UserDeviceAdmin内使用STATUS_CHOICES。你知道吗

STATUS_CHOICES = ((0, gettext("disabled")), (1, gettext("allowed")))

class UserDevice(BaseModel):
    """Table with all devices added and owned by users."""

    device_uniqueid = CharField(primary_key=True)
    device_user = ForeignKeyField(User, null=True, backref='userdevices')
    device_name = CharField()
    model = CharField()
    phone = CharField()
    status = IntegerField(choices=STATUS_CHOICES, default=1)
    inserted_at = DateTimeField(null=True)

    def myfunc(self):
        return self.a

class UserDeviceAdmin(ModelView):
    can_create = False
    edit_modal = True
    column_choices = {'status': STATUS_CHOICES}
    column_list = [
        'device_uniqueid',
        'device_user.email',
        'device_name',
        'model',
        'phone',
        'status',
        'inserted_at',
    ]
    column_sortable_list = ('device_uniqueid', 'device_user.email')
    form_ajax_refs = {'device_user': {'fields': ['email']}}

Tags: trueemaildevicestatuscolumnnullclasschoices
2条回答

把它移进去:

class UserDevice(BaseModel):
    """Table with all devices added and owned by users."""
    STATUS_CHOICES = ((0, gettext("disabled")), (1, gettext("allowed")))

从其他类访问它:

class UserDeviceAdmin(ModelView):
    can_create = False
    edit_modal = True
    column_choices = {'status': UserDevice.STATUS_CHOICES}

就像静态变量。你知道吗

您应该考虑使用父类,从中可以继承,这在python中很容易做到:

class Parent_class(object):
    def get_status_choices(self):
        return ((0, gettext("disabled")), (1, gettext("allowed")))


class UserDevice(BaseModel, Parent_class):
    # your implementation...
    status = IntegerField(choices=self.get_status_choices(), default=1)
    # and further implementations....

class UserDeviceAdmin(ModelView, Parent_class):
    # your implementation...
    column_choices = {'status': self.get_status_choices()}
    # and further implementations....

注意,最好将父类的名称更改为域中相关的名称

相关问题 更多 >