Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

python - Python增量对象名称[重复](Python Incremental object-names [duplicate])

Ever since I've learned the basics of Python classes I've had a single question on my mind: How do you automate the creation of objects instead of having to type test1 = class(example, test) every time?

(自从我学习了Python类的基础知识之后,我一直在思考一个问题:如何自动创建对象,而不必每次都键入test1 = class(example, test) ?)

I've tried using a static function within the class to create the function as such:

(我试过在类中使用静态函数来创建该函数,如下所示:)

class test:
       num_of_t = 0
       coomers = []
       def __init__(self, tes, t):
              self.test = tes
              self.t = t
              test.num_of_t += 1
       @staticethod
       def creat():
              example_input = input("test:")
              example_input2 = input("test2:")
              test.coomers.append("test_{}".format(test.num_of_t))
              for x in test.coomers:
                     x = test(example_input, example_input2)

def starter():
       while y<10:
              y += 1
              test.creat()

What the program is supposed to do is create 10 objects "test_1, test_2, test_3, etc" respectively with their own values for tes and t because of the 2 inputs.

(该程序应该执行的操作是创建10个对象“ test_1,test_2,test_3等”,分别使用tes和t的值,因为有2个输入。)

My problem is in x = test(example_input, example_input2) as it won't create the class as one would by typing test_1 = test(3, 7)

(我的问题是在x = test(example_input, example_input2)因为它不会像键入test_1 = test(3, 7) x = test(example_input, example_input2)那样创建类)

  ask by Nachtel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It would be better if you use a dictionary to save the created instances of the class like this :

(最好使用字典来保存创建的类实例,如下所示:)

def starter():
    key_list = [f'test_{i+1}' for i in range(10)]
    instance_dict = {}
    fixed_tes = 3
    fixed_t = 7
    for k in key_list:
        instance_dict[k] = test(fixed_tes, fixed_t)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...