简体   繁体   中英

calling class and function name from database in Python

I have some 20 class with functions in python:

class class_1:
    def display():
        return('This is 1st Class')

class class_2:
    def display():
        return('This is 2nd Class and some more lines')

#Like this 20 class I have

Now when to call which class, its stored in database:

tag class status
ab 2 0
cd 3 1
ef 1 0
gh 1 1

Now I when I run the below code:

data = db_fetchquery("SELECT class FROM table WHERE status = '0'")

for row in data:
    display = class_{row[0]}.display()
    print(display)

The result I am expecting is:

This is 2nd Class and some more lines

This is 1st Class

But I am getting SyntaxError: invalid syntax

I also tried dictionary:

data = db_fetchquery("SELECT class FROM table WHERE status = '0'")

for row in data:
   id = {'x' : 'class_'+row[0]}
   display = id['x'].display()

This gave me AttributeError: 'str' object has no attribute 'display'

The code below is the direction you need to take. The code takes input from the user (your code will replace it with DB call) and execute the proper function.

import inspect

import sys


def display_1():
    print('display_1')


def display_2():
    print('display_2')


funcs = {name: obj for name, obj in inspect.getmembers(sys.modules[__name__]) if inspect.isfunction(obj)}
func_id = input('Type func id:')
final_name = 'display_{}'.format(func_id)
func = funcs.get(final_name)
if not func:
    print('cant find the func ' + final_name)
else:
    func()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM