Utkarsh Singh
Utkarsh Singh

Reputation: 31

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>>]

I want that year(self) function to return the value of year variable but it is returning

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

Any idea how it can be achieved? Also, it will be great if the value can be returned as an integer.

Upvotes: 2

Views: 197

Answers (1)

Samuel Dion-Girardeau
Samuel Dion-Girardeau

Reputation: 3180

You're actually not that far from getting this to work!

The problem you have right now is that there is a conflict between the name year being a class attribute (this line: year = timelist[4]) but also a method name (this line: def year(self):.

You can update you code to the following:

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)

And you will correctly get this output: ['2019']

Note that here, I removed all the class variables, and fixed the __init__ implementation, so that each instance has its own current time. The crucial bit is that I'm using _year as the attribute name for the private value you store, and year for the function you want to use.

Upvotes: 2

Related Questions