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

У меня в классе есть вот такая конструкция:

class FilterCollection:
def __init__(self):
self.system = ''
self.customer = ''
self.status = ''

def get_by_name(self, name):
if (name == 'system'):
return self.system
elif(name == 'customer'):
return self.customer
elif(name == 'status'):
return self.status
Как можно переписать метод get_by_name(), чтобы он не увеличивался в размерах при увеличении количества переменных?
igor.kaist
вот….
class a:
def __init__(self):
self.a=5
self.b='test'
def get(self,name):return self.__dict__[name]
b=a()
b.get('a')
хотя такая организация ни к чему хорошему не приведет… :)
crchemist
def get(self,name):return self.__dict__ != def get_by_name(self, name)
crchemist
class FilterCollection:
def __init__(self):
self.system = ''
self.customer = ''
self.status = ''

def get_by_name(self, name):
return getattr(self, name, None)
crchemist
а взагалі правильніше писати так:
[crchemist@test ~]$ cat ss.py
ATTR_NAME = 'status'

class FilterCollection(object):
def __init__(self):
self.system = ''
self.customer = ''
self.status = '200 OK'

fc = FilterCollection()
if hasattr(fc, ATTR_NAME):
print getattr(fc, ATTR_NAME)
else:
print 'No such attribute'
[crchemist@test ~]$ python ss.py
200 OK
[crchemist@test ~]$
igor.kaist
А в чем разница?
crchemist
igor.kaist
А в чем разница?
в даному випадку нема: але є різниця для дескрипторів і атрибутів класу
[crchemist@test ~]$ cat ss.py
class A(object):
__slots__ = ('obj_attr_not_in_dict')

class_attr = 'i am class attr in class dict'
def __init__(self):
self.obj_attr_not_in_dict = 'i am object attr not in dict'

@property
def i_am_descriptor(self):
return 'i am not simple attr - i am descriptor'
[crchemist@test ~]$ python
Python 2.5.2 (r252:60911, Jul 5 2008, 03:54:54)
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ss import A
>>> a = A()
>>> a.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute '__dict__'
>>> a.obj_attr_not_in_dict
'i am object attr not in dict'
>>> a.__class__.__dict__.items()
[('__module__', 'ss'), ('i_am_descriptor', <property object at 0x956bd24>), ('class_attr', 'i am class attr in class dict'), ('obj_attr_not_in_dict', <member 'obj_attr_not_in_dict' of 'A' objects>), ('__slots__', 'obj_attr_not_in_dict'), ('__doc__', None), ('__init__', <function __init__ at 0x9569304>)]
>>> a.__class__.__dict__.get('i_am_descriptor')
<property object at 0x956bd24>
>>>
crchemist
атрибути класу зберігаються не в звичайному словнику а в dictproxy тому
>>> a.__class__.__dict__.get('i_am_descriptor')
<property object at 0x956bd24>
>>> a.i_am_descriptor
'i am not simple attr - i am descriptor'
ну але це не стосується обєктів
igor.kaist
Ну да, но для текущей задачи топикстартера хватит вполне… :)
crchemist
demas
Добрый день,

У меня в классе есть вот такая конструкция:

class FilterCollection:
def __init__(self):
self.system = ''
self.customer = ''
self.status = ''

def get_by_name(self, name):
if (name == 'system'):
return self.system
elif(name == 'customer'):
return self.customer
elif(name == 'status'):
return self.status
Как можно переписать метод get_by_name(), чтобы он не увеличивался в размерах при увеличении количества переменных?
Ще можна так:
class FilterCollection(object):
def __init__(self):
self.system = 'ss'
self.customer = ''
self.status = ''

get_by_name = object.__getattribute__
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