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.:
classA(object):@propertydefa(self):
return2
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:
classclassproperty(object):def__init__(self, f):
self.f = classmethod(f)
def__get__(self, *a):
returnself.f.__get__(*a)()
Now you can do:
classA(object):@classpropertydefa(self):
return2
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:
<propertyobject at 0x7f892bfb11b0>
<propertyobject at 0x7f892bfb1208>
2
@property only works properly on a class object that has been instantiated.
Post a Comment for "Property Method Without Class"