了解Python类实例化

2024-04-16 16:54:46 发布

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

试图找出本身就是类的类属性的类继承。我想做的是:

class foo:
    hello = None
    world = None

    def __init__(self, **kwargs):
        for k,v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)
            else:
                raise AttributeError(f'class foo has no attribute {k}')


class foo2:
    hi = None
    earth = None

    def __init__(self, **kwargs):
        for k,v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)
            else:
                raise AttributeError(f'class foo has no attribute {k}')

class bar:
    foo_attr = foo(hello=1, world=2)
    foo2_attr = foo2(hi=3, earth=4)


class bar2(bar):
    def __init__(self):
    super().__init__()

所以我有2个基类(foo and foo2),每个基类有2个属性(hello&worldhi&earth

我还有另一个基类(bar),它的类属性中有foofoo2的默认值

更新(包括问题):

最后,我有bar2,它是bar的一个子类。如何更改子类本身即类的属性值(在bar2)中foo\u attr的say hello属性

我试图为bar设置一个默认值,但我希望在对bar进行子类化时,能够为bar中的每个类属性设置不同的属性。这样,我就可以创建一堆bar的子类,如下所示:

一个bar2,除了foo2.earth(我将其设置为20)之外的默认属性。这意味着bar2有:

  • foo.hello=1
  • foo.world=2
  • foo2.hi=3
  • foo2.earth=20

然后仍然可以创建一个bar3,除了foo.hello之外,还可以使用foo()和foo2()的默认属性,可能我想设置为30,然后添加一个新属性say“jeez”

我该怎么做呢


Tags: selfnonehelloworld属性fooinitdef
2条回答

我认为您需要将该功能放入foofoo2中,如果这些功能继承自具有该功能的公共超类,那么重复性就会减少。下面的脚本可以工作(我不得不删除'f'字符串,因为我深陷在python3.5黑暗的旧时代)。实现bar子类仍有一些工作,但相对来说是合理的

import copy

class Fooinator:

    def __init__(self, **kwargs):
        badniks = self._update_instance(**kwargs)
        if badniks:
            raise AttributeError('class foo has no attributes {}'.format(badniks))

    def _update_instance(self, **kwargs):
        """Update self for variables defined at the class level returning
        names of variables not used by this class. """
        badniks = []
        for k,v in kwargs.items():
            if hasattr(self, k):
                setattr(self, k, v)
            else:
                badniks.append(k)
        return badniks

    def opt_clone(self, **kwargs):
        """Given keyword arguments, clone a copy of self if any of them are
        used by this class, else return self."""
        for k in kwargs:
            if hasattr(self, k):
                me_2 = copy.copy(self)
                me_2._update_instance(**kwargs)
                return me_2
        return self


class foo(Fooinator):
    hello = None
    world = None


class foo2(Fooinator):
    hi = None
    earth = None


class bar:
    foo_attr = foo(hello=1, world=2)
    foo2_attr = foo2(hi=3, earth=4)


class bar2(bar):
    foo2_attr = bar.foo2_attr.opt_clone(earth=20)

b = bar2()
print(b.foo_attr.hello, b.foo_attr.world, b.foo2_attr.hi, b.foo2_attr.earth)

看起来您想为barbar2创建显式构造函数,以便您可以选择以下属性:

class bar:
    def __init__(self, hello=1, world=2, hi=3, earth=4)
        self.foo_attr = foo(hello=hello, world=world)
        self.foo2_attr = foo2(hi=hi, earth=earth)

class bar2:
    def __init__(self)
        bar.__init__(self, earth=20)

您仍然可以在新类中添加新属性

相关问题 更多 >