11

I have a next code

global_variable = 1

@property
def method():
    # Some magic, for example 
    # incrementing global variable
    global global_variable
    global_variable += 1
    return global_variable

print method

This code return

<property object at 0x28dedb8>

But I expect 2. Is it possible in python to use property decorator outside a class?

glglgl
  • 89,107
  • 13
  • 149
  • 217
Rusty Robot
  • 1,305
  • 1
  • 12
  • 18

2 Answers2

13

@properties are meant to be instance properties, defined in a class. E.g.:

class A(object):
   @property
   def a(self):
      return 2

b = A()
b.a
=> 2

If I understand, you're trying to define a module-property (or "global" property). There's no easy/clean way to do that. See this related question.

EDIT: you can also define a classproperty, to make your property more global-like (does not required an instance). classproperty is not a built in, but is easy to define. Here's one way to define it:

class classproperty(object):
    def __init__(self, f):
        self.f = classmethod(f)
    def __get__(self, *a):
        return self.f.__get__(*a)()

Now you can do:

class A(object):
   @classproperty
   def a(self):
      return 2

A.a
=> 2
Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153
2

Observe the following code:

@property
def f():
    return 1

print f

class a(object):
    @property
    def f(self):
        return 2

print a.f
b = a()
print b.f

Output:

<property object at 0x7f892bfb11b0>
<property object at 0x7f892bfb1208>
2

@property only works properly on a class object that has been instantiated.

korylprince
  • 2,969
  • 1
  • 18
  • 27