如何使用 return 语句 return python 中 class 的变量?
How to return a variable of a class in python using return statement?
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)
函数 return year 变量的值,但它 returning
> [<bound method curtime.year of <__main__.curtime object at
> 0x00000285753E8470>>]
知道如何实现吗?此外,如果该值可以 return 为整数,那就太好了。
您实际上离实现它不远了!
您现在遇到的问题是名称 year
作为 class 属性(这一行: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']
请注意,我在这里删除了所有 class 变量,并修复了 __init__
实现,以便每个实例都有自己的当前时间。关键是我使用 _year
作为您存储的私有值的属性名称,并使用 year
作为您要使用的函数。
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)
函数 return year 变量的值,但它 returning
> [<bound method curtime.year of <__main__.curtime object at
> 0x00000285753E8470>>]
知道如何实现吗?此外,如果该值可以 return 为整数,那就太好了。
您实际上离实现它不远了!
您现在遇到的问题是名称 year
作为 class 属性(这一行: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']
请注意,我在这里删除了所有 class 变量,并修复了 __init__
实现,以便每个实例都有自己的当前时间。关键是我使用 _year
作为您存储的私有值的属性名称,并使用 year
作为您要使用的函数。