Уведомления

Группа в Telegram: @pythonsu

#1 Янв. 17, 2011 04:30:35

alexious
От:
Зарегистрирован: 2011-01-17
Сообщения: 2
Репутация: +  0  -
Профиль   Отправить e-mail  

запись и чтение переменной в классе

Добрый день,

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

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
Подскажите пожалуйста как такое сделать



Офлайн

#2 Янв. 17, 2011 12:05:02

Dimitor
От:
Зарегистрирован: 2007-10-30
Сообщения: 13
Репутация: +  0  -
Профиль   Отправить e-mail  

запись и чтение переменной в классе

Простите за банальность, но может так? :)

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.



Офлайн

#3 Янв. 18, 2011 00:17:11

alexious
От:
Зарегистрирован: 2011-01-17
Сообщения: 2
Репутация: +  0  -
Профиль   Отправить e-mail  

запись и чтение переменной в классе

Спасибо, сделал так

>>> 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'
>>>



Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version