【问题标题】:How to return a variable of a class in python using return statement?如何使用return语句在python中返回一个类的变量?
【发布时间】:2019-07-31 11:33:00
【问题描述】:
import time

class curtime:

    timeu = time.asctime(time.localtime(time.time())) 
    timelist = timeu.split()
    day = timelist[0]
    month = timelist[1]
    date = timelist[2]
    time = timelist[3]
    year = timelist[4]

    def __init__():
        timeu = time.asctime(time.localtime(time.time())) 
        timelist = timeu.split()
        day = timelist[0]
        month = timelist[1]
        date = timelist[2]
        time = timelist[3]
        year = timelist[4]

    def year(self):
        print([self.year])
        return [self.year]

t1 = curtime()
years = t1.year()
print(years)    # this is giving output as [<bound method curtime.year of <__main__.curtime object at 0x00000285753E8470>>]

我希望 year(self) 函数返回年份变量的值,但它正在返回

> [<bound method curtime.year of <__main__.curtime object at
> 0x00000285753E8470>>]

知道如何实现吗?此外,如果该值可以作为整数返回,那就太好了。

【问题讨论】:

  • _int_()?为什么要分配两次;一个内部功能和另一个外部?毕竟这里不需要上课。
  • 那是因为我无法猜测这些变量将使用的数据类型。字符串类型不适合我。

标签: python-3.x time python-3.7


【解决方案1】:

实际上离实现这个功能并不遥远!

您现在遇到的问题是名称 year 作为类属性(此行:year = timelist[4])和方法名称(此行:def year(self):)之间存在冲突。

您可以将代码更新为以下内容:

import time


class curtime:

    def __init__(self):
        timeu = time.asctime(time.localtime(time.time())) 
        timelist = timeu.split()
        self._day = timelist[0]
        self._month = timelist[1]
        self._date = timelist[2]
        self._time = timelist[3]
        self._year = timelist[4]

    def year(self):
        return [self._year]


t1 = curtime()
years = t1.year()
print(years)

你会正确得到这个输出:['2019']

注意这里,我删除了所有的类变量,并修复了__init__的实现,这样每个实例都有自己的当前时间。关键是我使用_year 作为您存储的私有值的属性名称,并使用year 作为您要使用的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多