0

次に、Pythonを学ぶための私の探求で、私は質問に出くわしました。プログラム内で変数を作成し、文字列を連結して名前を付け、オブジェクトを格納するために使用できますか?

だから、私のオブジェクト:

class Veg:
    def __init__(self, x):
        self.name = x
        print('You have created a new vegetable:', self.name, end='\n')

ここで、変数を作成するには:

tag = 1
newVegObj = 'veg' + str(tag) #Should create a variable named 'veg1'
newVegObj = Veg('Pepper') #Creates an object stored in 'newVegObj' :(

しかし、作成したオブジェクトを「veg1」に格納する必要があります。それから私はすることができます:

tag = tag + 1
newVegObj = 'veg + str(tag) #Create a variable named 'veg2'
newVegObj = Veg('Tomato')

目標は、veg1.name=Pepperおよびveg2.name=Tomatoであり、追加の野菜を格納するための追加の変数を継続的に作成できるようにすることです。

これが可能かどうかはわかりません。もしそうなら、そしてこれが複雑な解決策を必要とするならば、あなたは採用されたコードの役に立つ説明を提供できますか?うまくいけば、それは私が考えていない単純なものです。

前もって感謝します!君たちは最高です!

4

1 に答える 1

0

あなたのコメントを考えると、次のようなものが役立つかもしれません。

names = ['Tomato', 'Snoskommer', 'Pepper'] # a list containing 3 names
vegetables = {} # an empty dictionary

for name in names: # just textual: for each name in the names list ...
    new_veg = Veg(name) # create a new vegetable with the name stored in the variable 'name'
    vegetables[name] = new_veg # add the new vegetable to the vegetable dictionary

# at this point, the vegetables dictionary will contain a number of vegetables, which you can find by
# 'indexing' the dictionary with their name:
print(vegetables['Tomato'].name) # will print 'Tomato'

簡単なチュートリアルから始めるのが最善かもしれませんが、それがPythonのいくつかの基本を理解するのに役立つことを願っています:)


拡張するには、後で変更するために次のようなものを作成できます。

def add_vegetable(name):野菜に名前がある場合:print('その名前の野菜はすでにあります...')else:vegetables [name] = Veg(name)

野菜をリストに追加する関数を呼び出す:

add_vegetable('Cucumber')

その後、辞書には「キュウリ」という名前の別の野菜が含まれます。

しかし、繰り返しになりますが、いくつかの入門チュートリアルを実行すると、 http://python.orgでいくつかを紹介できるはずです。

于 2013-03-20T15:02:25.260 に答える