Jayron Hubbard
Jayron Hubbard

Reputation: 121

Instantiate multiple objects of a class most efficiently

I am writing some python code and I have a roman numeral class that I created. It works much the same as the built in roman() class. I want to instantiate roman numbers from 1 to 1000 without having to actually instantiate each one myself. For Example:

I = roman(1)
II = roman(2)
.... up to M = roman(1000)

Assuming I already have a way to convert numbers to roman numerals, what would be the most efficient way of doing this?

So someone should be able to import * from the roman module and type in something like:

IV * I + II * V

and get...

roman(14)

So in other words.. each roman numeral is its own object.

Upvotes: 1

Views: 213

Answers (2)

Kevin J. Chase
Kevin J. Chase

Reputation: 3956

As a Dictionary

Since you're essentially mapping strings like "IV" to objects of your roman class, you should probably keep them in a dictionary instead of the local namespace. Assuming your roman's __str__(self) method returns strings like "I" and "XV", you can declare the dictionary like this:

ROMANS = {
  str(r): r for r in (
    roman(i) for i in range(1, 1000 + 1)
    )
  }

Now you can access individual roman objects as ROMANS["XXIV"] and so on.

(That dictionary comprehension and generator expression combo is ugly enough that I would probably hide it in a function called _romans_dict(upper=1000).)

As a Bunch of Variables

If you really want to access the roman(7) object by way of a variable named VII, you can update your local namespace with the dictionary you just created. You can even throw away the dictionary's name after the update. (Fortunately, all-caps Roman numerals like "VII" match Python's naming conventions for module-level constants.)

# ROMANS = ...same as above
locals().update(ROMANS)
del(ROMANS)  # optional

The wisdom of spamming your module's namespace with a thousand or more Roman numerals is a different question. (For starters, my syntax checker screams at me for using variables like VII and XIX that it can't find declared anywhere. Your boss might scream at you, too.)

A Final Quibble

Your roman class should probably be spelled Roman. Python class names are (usually) in StudlyCaps.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361645

numerals = [roman(i) for i in range(1, 1001)]
print(numerals)

That'll give you a list of roman numerals from 1 to 1000. You can then access individual numbers if you wish. Note that the indices will be off by 1 since list indices start at 0 but roman numerals start at 1.

print(numerals[0])    # I
print(numerals[9])    # X
print(numerals[999])  # M

Upvotes: 0

Related Questions