0

Using Python, I would like to define multiple classes using a function. For example, I want to code something along the lines of:

def addClass(className, x, y):
    #Creates new class called className which contains definitions for x and y.

addClass("position", 100, 200)

#Expected Resulting Class:
#
#class position:
#    x = 100
#    y = 200

print(position.x)

#Expected Output:
#
#100

After defining multiple classes with this function, I'd like to be able to access the x and y values of all of those classes in the form className.x or className.y. Does anyone know how to accomplish this? Or if it is even possible? Or if there is a better way to accomplish the same task?

TBQTLS
  • 11
  • This is simply not a good idea. It doesn't save any typing; by using dataclasses, and it doesn't add any clarity. You can define your class with the same number of keystrokes. – Tim Roberts Apr 24 '22 at 03:43
  • Look at class factories, e.g. [this description](https://www.geeksforgeeks.org/class-factories-a-powerful-pattern-in-python/) – DilithiumMatrix Apr 24 '22 at 04:11
  • 1
    @TimRoberts No offense but...I don't think it should matter if what they are trying to do is a good idea or not. They just have something they wanna try, so just let them do that. With time, they'll learn the difference between good ideas and bad ideas. – Zero Apr 24 '22 at 05:00
  • There is most likely a solution not involving external libraries, but you can also do this with Pydantic's `create_model`: https://pydantic-docs.helpmanual.io/usage/models/#dynamic-model-creation – Gino Mempin Apr 24 '22 at 05:08
  • Does this answer your question? [How can I dynamically create derived classes from a base class](https://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class) – Gino Mempin Apr 24 '22 at 05:13
  • 1
    @IshanShishodiya -- I disagree completely. If someone is trying to pound in a nail with a banana, is it better to tell them how to do it, or to tell them to use a hammer? The PROBLEM they have has a simpler solution. That's what we need to provide. – Tim Roberts Apr 24 '22 at 05:21

2 Answers2

0

This is one way of doing this,

def addClass(className, x, y):
  return type(className, (object,), {"x": x, "y": "y"})

position = addClass("position", 100, 200)
print(position.x)

Output -

100
Zero
  • 1,800
  • 1
  • 5
  • 16
-1

I am not sure what is the reason for you to do this (there aren't too many), but here is one way:

def addClass(className, x, y):
    globals()[className] = type(className, (), dict(x=x, y=y))

addClass("position", 100, 200)

print(position.x)
jabbson
  • 4,390
  • 1
  • 13
  • 23