如何使用return语句在python中返回类的变量?

问题描述 投票:2回答:1
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)函数返回year变量的值,但它返回

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

知道如何实现它吗?此外,如果值可以作为整数返回,那将会很棒。

python-3.x time python-3.7
1个回答
0
投票

你实际上并没有那么远!

您现在遇到的问题是,名称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作为您要使用的函数。

© www.soinside.com 2019 - 2024. All rights reserved.