我有一个 python 模块,想调用所有常量

I have a python module and want to call all constants

我有一个 Lego mindstorms 51515 并且喜欢用 python 对它进行编程。

我想循环使用的模块中有一些默认图像。

import hub
images = dir(hub.Image)
print(images)

输出:

['__class__', '__name__', '__bases__', '__dict__', 'ALL_ARROWS', 'ALL_CLOCKS', 'ANGRY', 'ARROW_E', 'ARROW_N', 'ARROW_NE', 'ARROW_NW', 'ARROW_S', 'ARROW_SE', 'ARROW_SW', 'ARROW_W', 'ASLEEP', 'BUTTERFLY', 'CHESSBOARD', 'CLOCK1', 'CLOCK10', 'CLOCK11', 'CLOCK12', 'CLOCK2', 'CLOCK3', 'CLOCK4', 'CLOCK5', 'CLOCK6', 'CLOCK7', 'CLOCK8', 'CLOCK9', 'CONFUSED', 'COW', 'DIAMOND', 'DIAMOND_SMALL', 'DUCK', 'FABULOUS', 'GHOST', 'GIRAFFE', 'GO_DOWN', 'GO_LEFT', 'GO_RIGHT', 'GO_UP', 'HAPPY', 'HEART', 'HEART_SMALL', 'HOUSE', 'MEH', 'MUSIC_CROTCHET', 'MUSIC_QUAVER', 'MUSIC_QUAVERS', 'NO', 'PACMAN', 'PITCHFORK', 'RABBIT', 'ROLLERSKATE', 'SAD', 'SILLY', 'SKULL', 'SMILE', 'SNAKE', 'SQUARE', 'SQUARE_SMALL', 'STICKFIGURE', 'SURPRISED', 'SWORD', 'TARGET', 'TORTOISE', 'TRIANGLE', 'TRIANGLE_LEFT', 'TSHIRT', 'UMBRELLA', 'XMAS', 'YES', 'get_pixel', 'height', 'set_pixel', 'shift_down', 'shift_left', 'shift_right', 'shift_up', 'width']

所有只有大写字母的全名应该是我想循环的常量。

如何操作?

for dynamic_image in images:
    if not dynamic_image.isupper():
        continue
    var = hub.Image.{dynamic_image} # This is the real question on how to do this

通过字典理解获取 hub.Image 的所有仅大写的属性:

import hub
names = {name: getattr(hub.Image, name, None) 
         for name in dir(hub.Image) if name.isupper()}

这将给出所有常量的字典:名称及其值。例如打印出来,使用

print(list(var.items())

您可以使用 filter().isupper():

import hub
images = dir(hub.Image)
print(list(filter(lambda x: x.isupper(), names))) # Strings with uppercase letters and underscores only
print(list(filter(lambda x: x.isupper() and x.isalpha(), names))) # Strings with uppercase letters only (no underscores)

我解决了,答案如下:

import hub
import time

images = dir(hub.Image)
while True:
    for image in images:
        if image.upper() != image:
            continue
        print(image)
        img = hub.Image.__dict__[image]  # This was what I was looking  for
        hub.display.show(img)
        time.sleep(1)