仅在基类中获取属性(Python) [英] Get attributibutes in only base class (Python)

查看:70
本文介绍了仅在基类中获取属性(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下类结构:

class Parent(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

    def print_vars(self):
        print(vars(self))

class Child(Parent):
    def __init__(self, id, name, last_name, age):
       Parent.__init__(self, id, name)
       self.last_name = last_name
       self.age = age

class AnotherChild(Parent):
    def __init__(self, id, name, address):
       Parent.__init__(self, id, name)
       self.address= address

也许不是最好的例子,但我希望有足够的机会让这个想法传开.我的想法是初始化两个共享一些共同属性和方法的单独实例.我需要能够将两个对象都转储到我希望使用方法dump_to_file(在本示例中由print_vars代替)实现的json和csv文件中.现在,当我必须将父类和子类的所有属性都转储到单个文件中时,此方法可以正常工作.但是,我只想从父类中转储属性.我试图将self替换为supersuper(Parent, self),但没有成功.从代码编写类访问 only 属性的最佳方法是什么?

Perhaps not the best example, but I hope enough to get the idea accross. The idea is that I initialise two seperate instances that share some common attributes and methods. I need to be able to dump both objects into some json and csv files which I hope to achieve with the method dump_to_file (replaced by print_vars in this example). Now this method worked fine when I had to dump all the attributes from both the parent and child classes to a single file. Howeer, I want to only dump the attributes from the parent class. I tried to replace self by super or super(Parent, self) but without much success. What is the best way to access only the attributes from the class the code is written in?

我相信Java将自动执行此操作,因为方法是在父类中定义的,并且父类不知道子类的属性.

I believe Java would do this automatically as the method is defined in the parent class, and the parent class does not know the child class attributes.

推荐答案

假设您不打算在__init__之外添加更多变量,则可以冻结父级__init__方法中的变量列表:

Assuming that you aren't going to add more variables outside __init__, you could freeze the list of variables in the __init__ method of the parent:

def __init__(self, id, name):
    self.id = id
    self.name = name
    self.__parent_vars = dict(vars(self))  # make a copy

然后使用此字典,该字典仅包含您在初始化父类时定义的变量:

then use this dictionary, which has only the variables you defined when you initialized the parent class:

def print_values(self, path):
    print(self.__parent_vars)

测试:

c = Child(12,"Foo","whatever",34)
c.print_vars()

我得到:

{'id': 12, 'name': 'Foo'}

这篇关于仅在基类中获取属性(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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