Home > Software engineering >  Defining Classes using a Function
Defining Classes using a Function

Time:04-24

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?

CodePudding user response:

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

CodePudding user response:

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)
  • Related