0

Требуется цикл, создающий список из строки и кортежа, кортеж берется из модуля, название кортежа совпадает с названием строки. Возможно ли обозначить переменную как Имя_модуля.значение строки

Main:

import Color
stuff = ["apple", "banana"]
stuff_n_color = []
i = 0
while i < len(stuff):
    stuff_n_color[i] = [stuff[i], Color.stuff[i]]
    i += 1
i = 0

Color:

apple = (255, 0, 0)
banana = (255, 255, 0)
0

1 ответ 1

0

Обычно все переменные объектов (в т.ч. модулей, классов и так далее) лежат в словаре скрытым под атрибутом __dict__ к ним же можно обращаться как с обычным словарем.

Пару примеров:

class A():
    def __init__(self):
         pass

exmp_a = A()
exmp_a.b = 5
print(exmp_a.__dict__['b']) # output: 5

Еще один пример с стандартной библиотекой:

import math

print(math.__dict__)

# output: {'__name__': 'math',
 '__doc__': 'This module provides access to the mathematical functions\ndefined by the C standard.',
 '__package__': '',
 '__loader__': _frozen_importlib.BuiltinImporter,
 '__spec__': ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'),
 'acos': <function math.acos(x, /)>,
 'acosh': <function math.acosh(x, /)>,
 'asin': <function math.asin(x, /)>,
 'asinh': <function math.asinh(x, /)>,
 'atan': <function math.atan(x, /)>,
 'atan2': <function math.atan2(y, x, /)>,
 'atanh': <function math.atanh(x, /)>,
 'ceil': <function math.ceil(x, /)>,
 'copysign': <function math.copysign(x, y, /)>,
 'cos': <function math.cos(x, /)>,
 'cosh': <function math.cosh(x, /)>,
 'degrees': <function math.degrees(x, /)>, ... }

Т.е. в вашем случае, если в Color есть переменная с именем stuff[i], то к ней можно обратиться через Color.__dict__[stuff[i]]

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.