0

Suppose I want the following psuedocode to work

method generateClass(string name, <string,type>[] attributes)
       class name()
             //used like int a 
             //          char b
             attributes[0].[0] attributes[0].[1]
             attributes[1].[0] attributes[1].[1]

How would I do it in python?

Dr. John A Zoidberg
  • 1,168
  • 2
  • 14
  • 25
  • How is `attributes` organized? – Neo Jun 29 '16 at 08:50
  • 3
    Create a new type using [the 3-argument form of `type()`](https://docs.python.org/3/library/functions.html#type). – Ilja Everilä Jun 29 '16 at 08:51
  • In my psuedocode that should be an array of tuples, but the implementation can take whatever arguments are convenient. – Dr. John A Zoidberg Jun 29 '16 at 08:51
  • @IljaEverilä could you give a usage example? I'm not sure that I understand, but the documentation makes it look like that returns an instance of a class, rather than a class itself. – Dr. John A Zoidberg Jun 29 '16 at 08:54
  • 2
    @Dr.JohnAZoidberg no, it returns a class object. Also you don't type attributes in Python, so your pseudocode doesn't really translate. Do you have some actual code to demonstrate your attempts to implement this so far? – jonrsharpe Jun 29 '16 at 08:54
  • From the documentation: `X = type('X', (object,), dict(a=1))` creates a new type (class) `X` with a single base class `object` and class attribute `a` that has value *1*. – Ilja Everilä Jun 29 '16 at 08:59
  • I'm asking how to implement it because I wouldn't know where to start. from what I can see `class x: x = type('ABC', (object,), dict(a=1))` creates a class abc that inherets object. – Dr. John A Zoidberg Jun 29 '16 at 09:00
  • @IljaEverilä great! could you implement multiple class attributes? can you leave the class attributes unassigned? – Dr. John A Zoidberg Jun 29 '16 at 09:04
  • 1
    It seems to me that you should start by reading the [python tutorial](https://docs.python.org/3/tutorial/) to get a grasp on basic concepts and things that differ from for example Java. – Ilja Everilä Jun 29 '16 at 09:05
  • 1
    @Dr.JohnAZoidberg no, just `x = type('ABC', (object,), dict(a=1))` creates a new class. You don't use the `class` keyword in this context. You can create multiple attributes by adding them to the dictionary you are passing in. Python is dynamic, so you don't necessarily need to set them at class creation time. Leaving them unassigned makes no sense, they either don't exist or are assigned to something (even if that something is `None`). – jonrsharpe Jun 29 '16 at 09:06
  • 1
    Of course, what ever you pass in the dictionary used as namespace becomes the attributes. That includes functions. – Ilja Everilä Jun 29 '16 at 09:06
  • 1
    @Dr.JohnAZoidberg This is well worth a read: http://stackoverflow.com/a/6581949/172176 – Aya Jun 29 '16 at 09:53

0 Answers0