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?
@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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With