2
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.

2
  • _int_()? Why do you assign twice; one inside function and other outside? There is no need of a class here afterall. Commented Mar 9, 2019 at 17:33
  • That is because I was unable to guess the data type those variables will be using. String type was not working for me. Commented Mar 10, 2019 at 3:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.