【问题标题】:Python 3.xx : Classes in classesPython 3.xx:类中的类
【发布时间】:2017-03-22 09:19:09
【问题描述】:

我的 python 脚本需要帮助。如何通过 Date 的类访问我的时钟功能?

from datetime import date
from datetime import datetime

class Date(object):
    def date_today(self):
        now = date.today()
        print (now)

class Time(Date):
    pass
    def clock(self):
        hr = datetime.now()
        hr_now = hr.hour
        print (hr_now)

cr_date = Date()
print (cr_date.date_today())
print (cr_date.date_today.clock())

我收到一个错误 --> AttributeError: 'function' object has no attribute 'clock'。这个错误的原因是什么?

【问题讨论】:

  • 是的,你的 Date 类没有 clock() 函数。
  • 我有2个类,日期类和时间类我只想通过日期类访问时间类,你有什么建议吗?

标签: python python-3.x class subclassing


【解决方案1】:

您还可以在时间类中添加分钟、秒和其他相关功能。我希望它会有所帮助。

from datetime import date
from datetime import datetime

class Time():
    def clock(self):
        hr = datetime.now()
        hr_now = hr.hour
        return hr_now

class Date():
    def __init__(self):
        self.time = Time()

    def date_today(self):
        now = date.today()
        return now

    def clock(self):
        return self.time.clock()




cr_date = Date()

print(cr_date.date_today())
print(cr_date.clock())

【讨论】:

  • 非常感谢哈伦先生。这对我有帮助
  • 这个脚本 cr_date.date_today.clock() 是什么意思? (在我之前的脚本中)
  • 你不必这样调用。在您的问题中 date_today() 是一个函数,并且没有 clock() 函数作为属性,因此会引发错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 2019-05-29
  • 2017-05-29
  • 2017-09-21
  • 2021-12-30
  • 2012-01-05
相关资源
最近更新 更多