0
class pupil(object):
    name = 'name'
    mark = 0
    classOfPupil = 0


variable = bob

variable = pupil()

print(bob.name)

variable = steve

variable = pupil()

print(steve.name)

I want to know how to make as many instances as I want from a changing variable, for example, everytime someone inputs their information, for their information to be under a new instance of their name.

Flux
  • 25
  • 8

1 Answers1

0

You can do it like this:

globals()['bob'] = pupil()

or with a variable like this:

pupil_names = ['bob', 'bill', 'ted']
for pupil_name in pupil_names:
    globals()[pupil_name] = pupil()
    globals()[pupil_name].name = pupil_name

print bob.name  # 'bob'

Although not sure I'd recommend it in practice, there are nicer ways to do this.

Edit: For example, use your own dictionary instead:

pupils = {}
pupils['bob'] = pupil()
pupils['bob'].name = 'bob'

Safer and easier.

101
  • 8,514
  • 6
  • 43
  • 69
  • Would you be able to replace "['bob']" with a variable instead of a string? – Flux Jan 26 '15 at 08:21
  • It's definitely not recommended in practice... you run the risk of clobbering names (what if someone does `bob=3` - they might now have over-ridden the `pupil()` object, or the `pupil()` object might over-ride the user's `bob`). Worse still, because it's `globals()` you can end up affecting names outside the local scope which will cause unpleasant surprises and be a debugging nightmare - eg: What if I had a function called `bill` in my module, later on down the line it's now suddenly no longer a function, but a `pupil` object... Ouch :( – Jon Clements Jan 26 '15 at 09:02
  • @JonClements Well I suppose Python always has the risk of clobbering names e.g. `bob = Thing(); bob = 3` so care is always required. But agreed this is not a good piece of code to use in the real world! – 101 Jan 26 '15 at 09:06
  • Of course you can always clobber names - but that's more common at the same scope - the caller scope doesn't generally expect the callee to modify its state. `bill = 3` inside a function will bind locally, you'd have to use `global bill` and that's at least an indication you intend to do something (and debug tools will be able to trace it)... Modifying `globals()` obscures that fact... – Jon Clements Jan 26 '15 at 09:10