Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property method without class [duplicate]

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?

like image 742
Rusty Robot Avatar asked Jun 09 '13 08:06

Rusty Robot


2 Answers

@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
like image 63
shx2 Avatar answered Oct 12 '22 07:10

shx2


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.

like image 23
korylprince Avatar answered Oct 12 '22 08:10

korylprince