如何在类定义中调用类函数? [英] How do I call a class function inside the class definition?

查看:95
本文介绍了如何在类定义中调用类函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MetaData():

    maxSize = 2**10

    # class definition code
    if not os.path.exists('sample.data'):
        SSD  = open('sample.data', 'wb+')
        data = {
            0: [],
            1: {'.': None,}
        }
        data[1]['~'] = data[1]

        MetaData.save()  # i want to call the save function here


    # class function
    @classmethod
    def save(cls):

        cls.SSD.seek(0)
        cls.SSD.write(b' ' * cls.maxSize)
        cls.SSD.seek(0)
        cls.SSD.write(pickle.dumps(cls.data))

我想在类块内使用 save()函数.我试过 MetaDate.save()和简单地 save()都抛出错误

I want to use the save() function inside the class block. I've tried MetaDate.save() and simply save() both of which throw errors

有什么办法可以做到这一点?

Is there any way to achieve this?

修改

是的, maxSize 是一个类var,是的,我可以使用 cls.maxSize 来访问它.

Yes, maxSize is a class var and yes i can access it using cls.maxSize.

推荐答案

这是另一个答案.

您可以使用元类来解决无法在类主体中引用该类的限制(因为该类尚不存在).您可以在元类 __ new __()方法中创建该类,然后对其进行修改—在这种情况下,可以通过调用其中定义的类方法进行修改.这就是我的意思:

You can use a metaclass to workaround to the limitation that you can't reference the class in the class body (since the class doesn't exist yet). You can create the class in the metaclass __new__() method and then modify it — in this case by calling a classmethod defined in it. Here's what I mean:

import os
import pickle


class MetaMetaData(type):
    def __new__(meta, classname, bases, classdict):

        cls = type.__new__(meta, classname, bases, classdict)

        if not os.path.exists('sample.data'):
            cls.SSD = open('sample.data', 'wb+')

            cls.data = data = {
                0: [],
                1: {'.': None,}
            }
            data[1]['~'] = data[1]

            cls.save()

        return cls


class MetaData(metaclass=MetaMetaData):
    maxSize = 2**10

    @classmethod
    def save(cls):
        cls.SSD.seek(0)
        cls.SSD.write(b' ' * cls.maxSize)
        cls.SSD.seek(0)
        cls.SSD.write(pickle.dumps(cls.data))

    # class definition code
    ...


if __name__ == '__main__':
    print(MetaData.data)

第一次运行时产生的输出(即没有预先存在的 sample.data 文件时):

Output produced from running it for the first time (i.e. when there was no preexisting sample.data file):

{0: [], 1: {'.': None, '~': {...}}}

请注意, SSD 类属性是一个打开的文件-这很奇怪,但是如果代码可运行的话,这也是您的代码也会做的事情.

Note that the SSD class attribute is an open file — which is very strange, but that's what your code would do too, if it were runnable.

这篇关于如何在类定义中调用类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆