为了账号安全,请及时绑定邮箱和手机立即绑定

在 __init__ 中设置属性

在 __init__ 中设置属性

万千封印 2021-06-25 15:05:16
我想B从A并使用__init__from创建一个子类,A因为它最多与一个属性/属性相同。以下代码显示了我想做的事情class A:    def __init__(self):        self.a = 1        self.b = 1        self.c = 1class B(A):    def __init__(self):        super().__init__()  # because I want 'a' and 'b', (but not 'c')    @property    def c(self):        return 2B()追溯:---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)<ipython-input-9-95c544214e48> in <module>()     13         return 2     14 ---> 15 B()<ipython-input-9-95c544214e48> in __init__(self)      7 class B(A):      8     def __init__(self):----> 9         super().__init__()  # because I want 'a' and 'b', (but not 'c')     10      11     @property<ipython-input-9-95c544214e48> in __init__(self)      3         self.a = 1      4         self.b = 1----> 5         self.c = 1      6       7 class B(A):AttributeError: can't set attribute我以为我可以通过做来解决这个问题class B(A):    def __init__(self):        super().__init__()  # because I want 'a' and 'b', (but not 'c')        self.c = property(lambda s: 2)但是,当然后调用:>>> B().c<property at 0x116f5d7c8>不评估该属性。我怎样才能正确地做到这一点,而无需手动复制__init__从A?
查看完整描述

1 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

一种补救方法是也c变成财产A;该属性仅返回(私人)成员self._c:


class A:

    def __init__(self):

        self.a = 1

        self.b = 1

        self._c = 1


    @property

    def c(self):

        return self._c


class B(A):

    def __init__(self):

        super().__init__()  # because I want 'a' and 'b', (but not 'c')

        self._c = 2


    # is already inherited from A

    # @property

    # def c(self):

    #     return self._c


a = A()

b = B()

print(a.c)  # 1

print(b.c)  # 2

如果你不能改变A(并假设你的财产的目的是使c只读),这是一个变体:c.setter如果self._c不是,将引发错误None:


class A:

    def __init__(self):

        self.a = 1

        self.b = 1

        self.c = 1


class B(A):

    def __init__(self):

        self._c = None

        super().__init__()  # the setter for c will work as self._c = None

        self._c = 2         # now we set c to the new value 

                            # (bypassing the setter)


    @property

    def c(self):

        return self._c


    @c.setter

    def c(self, value):

        if self._c is not None:

            raise AttributeError

        self._c = value


查看完整回答
反对 回复 2021-06-29
  • 1 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号