user2785724
user2785724

Reputation: 188

Python class property decorators not working

I'm trying to get Python's decorators to work for me. I'm having trouble understanding why this doesn't work:

class toy(object):

    @property
    def toyname(self):
        return 'lol'

a = toy
print(a.toyname)

when I run it, I get the following output:

<property object at 0x03362FC0>

The property, it seems, is not being evaluated.

I've seen several answers for Python 2.x mention that I need to subclass object in order for properties to work; however, the answers I've come across so far do not solve my problem.

Upvotes: 1

Views: 103

Answers (2)

daveruinseverything
daveruinseverything

Reputation: 5167

toy is the blueprint for your class. toy() is a new copy of the class that you can work with, or a new instance. You need to "instantiate" it, which means you need to create a new instance of the class to assign to a. In other words, you need a = toy() instead of a = toy

Try this:

class toy(object):
    @property
    def toyname(self):
        return 'lol'

a = toy()
print(a.toyname)

Upvotes: 1

mprat
mprat

Reputation: 2471

It's the line a = toy that is causing a problem. What a = toy means is saying is "point the variable a to the definition of the class toy". What you actually want to do is a = toy(), to instantiate an object of type toy and save it in a.

Upvotes: 4

Related Questions