从父类继承变量

2024-04-16 21:51:50 发布

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

我正在尝试解决如何从父类继承变量。你知道吗

我有两个班(简化但原理相同):

class Database(object):

    def __init__(self, post, *args, **kwargs):
        self.post = post

        self.report()

    def report(self):
        #... obtain variables from post ...
        self.database_id = self.post['id']

        #... save data to database



class PDF(Database):

    def __init__(self, post,  *args, **kwargs):
        Database.__init__(self, post, *args, **kwargs)

       #... if i try to access self.database_id now, it returns an error ...
       print(self.database_id)

实例化脚本:

        Database(request.POST)
        PDF(request.POST)

我试过实例化CreatePDF,因为我认为Database.__init__(self, post, *args, **kwargs)行将是数据库类,但这也不起作用。你知道吗

我正试图找到一种最适合做继承的方式。我显然可以得到self.u id数据库从post dict传递到PDF(),但是如果我可以使用继承的话,我不认为这样做有什么意义。你知道吗

谢谢


Tags: to实例selfreportidpdfinitrequest
1条回答
网友
1楼 · 发布于 2024-04-16 21:51:50

用途:

class PDF(Database):
    def __init__(self, post, *args, **kwargs):
        # Stuff
        super().__init__(post, *args, **kwargs)

实例化继承类的正确方法是调用super()。init(args),在本例中,它调用数据库。init,因为方法解析顺序。你知道吗

http://amyboyle.ninja/Python-Inheritance

相关问题 更多 >