Форум сайта python.su
Добрый день,
У меня есть класс с переменной в которую я хочу писать и из которой я хочу читать используя одну и туже функцию.
class editField(object):
value = "Read"
@property
def text(self):
return self.value
test = editField()
print test.text
>> Read
test = editField()
print test.text
>> Read
test.text = "Write"
print test.text
>> Write
Офлайн
Простите за банальность, но может так? :)
class Empty:
pass
test = Empty()
test.text = "TEST" # присваивание
print test.text # чтение
2.1 Built-in Functions
…
property( [fget[, fset[, fdel]]])
Return a property attribute for new-style classes (classes that derive from object).
fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x:If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:class C(object):
def __init__(self): self._x = None
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")turns the voltage() method into a ``getter'' for a read-only attribute with the same name.class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
Офлайн
Спасибо, сделал так
>>> class editField(object):
... def __init__(self):
... self.value = "Read"
... @property
... def text(self):
... return self.value
... @text.setter
... def text(self, val):
... self.value = val
...
>>> test = editField()
>>> test.text
'Read'
>>> test.text = "Write"
>>> test.text
'Write'
>>>
Офлайн