kangfend
kangfend

Reputation: 365

Call attribute method python

I want to display hour when i call date.now.hour but I get this error

AttributeError: 'function' object has no attribute 'hour'

this is my code:

#!/usr/bin/python

class Date:
    def now(self):
        self.hour = "hour"
        print "Now"
    
    def __call__(self, string):
        print string    
    
date = Date()
date('hello') # print hello
date.now.hour # print hour

My task is

Make a class that can do this:

date.now() - output: 'now'

date('hai') - output: 'hai'

date.now output: 'now'

date.now.hour output: 'hour'

Upvotes: 0

Views: 5951

Answers (5)

glglgl
glglgl

Reputation: 91099

You are quite close - one of your tasks are already done:

date('hai') - output: 'hai'

What is still left to do is

date.now() - output: 'now'

date.now - output: 'now'

date.now.hour output: 'hour'

So your date.now has quite a lot of requirements which only can be accomplished with a separate class:

class Now(object):
    def __str__(self): return ...
    def __call__(self): return ...
    hour = property(lambda self: 'hour')
    

or something like this.

This class you can use inside your class Date.


Another option would be to have now be a property of your class Date, but this would work analogous. You'd need a class Now like above, but you would it use like

class Date(object):
    def __call__ # as before
    @property
    def now(self):
        return Now()

Upvotes: 2

unddoch
unddoch

Reputation: 6004

date.hour is the right approach. You assign hour to the object (self), not to the function.

However, initializing instance attributes in methods is error-prone and a bad habit. You should redefine an __init__ method like this:

class Date:
    def __init__(self):
        self.hour = 'hour'

Upvotes: 1

alecxe
alecxe

Reputation: 474003

now is a method on Date class, hour is an attribute:

date = Date()
date('hello') # print hello
date.now() # print Now
print date.hour # print hour

Upvotes: 2

robjohncox
robjohncox

Reputation: 3665

The now function is setting the attribute hour on your class. If you do the following you should see the hour printed:

date = Date()
date.now()
date.hour

Upvotes: 2

Henrik Andersson
Henrik Andersson

Reputation: 47202

Just call it date.now() - you'll never be able to access the hour attribute of the function since it's an attribute of the object.

Doing date.hour will allow you to see hour.

>>> date.hour
'hour'

What you should do though is set all of these properties in the __init__ function of your class.

class Date():
    def __init__(self, hour):
        self.hour = hour

    def now(self):
       print self.hour #if you will

    def __call__(self string):
       print string

Upvotes: 5

Related Questions