Property Method Without Class
I have a next code global_variable = 1 @property def method(): # Some magic, for example # incrementing global variable global global_variable global_variable +=
Solution 1:
@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
Solution 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.
Post a Comment for "Property Method Without Class"