Найти - Пользователи
Полная версия: запись и чтение переменной в классе
Начало » Python для новичков » запись и чтение переменной в классе
1
alexious
Добрый день,

У меня есть класс с переменной в которую я хочу писать и из которой я хочу читать используя одну и туже функцию.

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
Подскажите пожалуйста как такое сделать
Dimitor
Простите за банальность, но может так? :)

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:

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.")
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 Parrot(object):
def __init__(self):
self._voltage = 100000

@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
turns the voltage() method into a ``getter'' for a read-only attribute with the same name.
alexious
Спасибо, сделал так
>>> 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'
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB