Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅在基类(Python)中获取属性属性_Python_Inheritance - Fatal编程技术网

仅在基类(Python)中获取属性属性

仅在基类(Python)中获取属性属性,python,inheritance,Python,Inheritance,我的班级结构如下: 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

我的班级结构如下:

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
也许这不是最好的例子,但我希望能有足够的理由让大家接受这个想法。我的想法是初始化两个单独的实例,它们共享一些公共属性和方法。我需要能够将这两个对象转储到一些json和csv文件中,我希望通过方法
dump\u to\u file
(在本例中由
print\u vars
代替)来实现这一点。现在,当我必须将父类和子类的所有属性转储到单个文件时,这个方法工作得很好。然而,我只想从父类中转储属性。我试图用
super
super(父母,自己)
取代
self
,但没有多大成功。只有从编写代码的类中访问属性的最佳方法是什么


我相信Java会自动做到这一点,因为方法是在父类中定义的,父类不知道子类属性

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

def __init__(self, id, name):
    self.id = id
    self.name = name
    self.__parent_vars = dict(vars(self))  # make a copy
然后使用此字典,它只包含初始化父类时定义的变量:

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

c = Child(12,"Foo","whatever",34)
c.print_vars()
我得到:

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

我目前面临同样的问题,并试图找到解决办法。 的答案不能解决我自己的问题-它在初始化子类时冻结了参数值,如果它将来发生变化,您的子类永远不会知道

我做了一些修改来修复它:

class Parent(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.__parent_vars = ['id', 'name']  # make a copy

    def print_values(self):
        res = {}
        for el in self.__parent_vars:
            res[el] = vars(self)[el]
        return res


class Child(Parent):
    def __init__(self, id, name, last_name, age):
        Parent.__init__(self, id, name)
        self.last_name = last_name
        self.age = age
让我们测试一下:

c = Child(12,"Foo","whatever",34)
res1 = c.print_values()
print(res1)

c.id = 24
res2 = c.print_values()
print(res2)
输出:

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

现在它像我预期的那样工作,但是我需要为它创建额外的变量。例如,如果我想pickle,我的类也会pickle这个我不需要的额外变量是否可以在不创建其他变量的情况下执行相同的操作?

为什么不创建父对象,然后调用该方法。因为变量的值可能是different@Jean-弗朗索瓦·法布♦ 我加了一些修改,你能看一下吗?我需要发布新问题吗?是的,当然你应该将你的答案作为一个问题发布,链接到这个问题,为什么不。但是删除这个不是真正答案的答案。谢谢