Home > Net >  Picking a random class from a file of classes Python
Picking a random class from a file of classes Python

Time:07-20

I have a python file filled with 161 different classes. I am trying to pick one class randomly from the file to be used in the main section of my program. I initially started using Pythons random choosing a number between 1 and 161 then writing out a match pattern to select one corresponding to a number. After completing 4 of these I realised it was going to take hours and could not find an alternative online. Thank you for any help.

For reference, the file with all the classes is named "champions.py" and I only need to take the title for each class. E.g. for the following class I only want to take "aatrox"

class aatrox:
    name = "Aatrox"
    gender = "Male"
    position = ["Top", "Middle"]
    species = ["Darkin"]
    resource = "Manaless"
    rangeType = "Melee"
    region = ["Noxus"]
    releaseYear = 2019

CodePudding user response:

You can try to put all of your class in a list and then randomly select a class from that list using the random library built into Python.

from champions import *
# so you don't have to write champions.this champions.that
import random # random module
classes = [aatrox, other_class, also_other_class]
chosen_class = random.choice(classes)

chosen_class is going to be a class.

Reference How can I get a list of all classes within current module in Python? for not needing to type all of the class names.

CodePudding user response:

This is an example of using the inspect library to get all classes in a module:

import inspect
import collections

def get_classes(module):
    class_members = inspect.getmembers(module, inspect.isclass)
    module_name = module.__name__
    return [cls for _, cls in class_members if cls.__module__ == module_name]

print(get_classes(collections))

Output:

[<class 'collections.ChainMap'>, <class 'collections.Counter'>, <class 'collections.OrderedDict'>, <class 'collections.UserDict'>, <class 'collections.UserList'>, <class 'collections.UserString'>, <class 'collections._Link'>, <class 'collections._OrderedDictItemsView'>, <class 'collections._OrderedDictKeysView'>, <class 'collections._OrderedDictValuesView'>, <class 'collections.defaultdict'>, <class 'collections.deque'>]

Then randomly select from the class list:

import random

cls = random.choice(get_classes(your_module))
  • Related