时钟程序继承帮助Python

2024-04-26 18:52:49 发布

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

我使用类和继承在Python上创建时钟。我试图在继承日历和时钟的Fecha类中创建一个函数advance()。我试图调用属性self.\uhora,但是我得到“属性错误:Fecha对象没有属性…”。我将只发布部分代码,因为它有点大:

class Reloj(object):

    __segundo = Contador(0, 60)
    __minuto = Contador(0, 60)
    __hora = Contador(0, 24)

    def __init__(self, s, minu, h):

        self.__segundo.setCuenta(s)
        self.__minuto.setCuenta(minu)
        self.__hora.setCuenta(h)


    def set(self, s, minu, h):

        self.__segundo.setCuenta(s)
        self.__minuto.setCuenta(minu)
        self.__hora.setCuenta(h)

    def tic(self):

        self.__segundo.contar()

类Reloj稍微大一点,但其余的只是显示函数。这是Fecha类:

class Fecha(Reloj, Calendario):

def __init__(self,d,m,a,s,minu,h):

    Reloj.__init__(self,s,minu,h)
    Calendario.__init__(self,d,m,a)

def avanzar(self):

    hora_previa= self.__hora
    Reloj.tic(self)
    if self.__hora < hora_previa:
        self.avanzar()

def __str__(self):

     return Calendario.__str__(self) +","+ Reloj.__str__(self)

Tags: self属性initdef时钟strcontadorfecha
3条回答

self.__hora是“privat”。试试这个self._Relog__hora。你知道吗

不要在变量前使用__,而不是:

__segundo = Contador(0, 60)
__minuto = Contador(0, 60)
__hora = Contador(0, 24)

你可以用这个:

_segundo = Contador(0, 60)
_minuto = Contador(0, 60)
_hora = Contador(0, 24)

你的AttributeError与你正在使用的属性名有关。当用两个下划线作为属性名的前缀时,这将调用Python的名称损坏系统。它将名称从__Foo转换为_SomeClass__Foo(如果代码在SomeClass类中)。它旨在帮助您编写mixin和代理类,而不必担心无意中的名称冲突。你知道吗

除非你真的需要,否则你不应该使用这个功能。如果属性是私有的,请重命名为只使用一个下划线。或者只是给他们公开的名字,不要费心去隐藏实现细节。你知道吗

您没有显示正在使用的Contador类型的代码。如果它不是一个花哨的描述符之类的东西,那么当您在Reloj中将它的实例赋给类变量时,您可能用错了它。您可能希望属性成为实例变量。我建议你这样做:

class Reloj(object):

    def __init__(self, s, minu, h):

        self._segundo = Contador(0, 60)
        self._minuto = Contador(0, 60)
        self._hora = Contador(0, 24)
        self.set(s, minu, h)

    ...

通过调用set,我们可以避免在__init__中复制它的代码,这只需要正确设置属性。前面的代码可能在每个Reloj实例之间共享时间值。你知道吗

相关问题 更多 >