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>>]
有什么想法可以实现吗?另外,如果该值可以作为整数返回,那将是很好的。
答案 0 :(得分:0)
您实际上离将其付诸实践不远!
您现在遇到的问题是,名称year
作为类属性(此行:year = timelist[4]
)与方法名称(此行:{{1})之间存在冲突}。
您可以将代码更新为以下内容:
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
用作要使用的函数。