使用Python在运行时创建对象 [英] Creating objects during runtime in Python
问题描述
在运行时创建对象时,我很难理解OOP概念.我研究过的所有教育法规都定义了特定的变量,例如'Bob'并将它们分配给一个新的对象实例.鲍勃= Person()
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()
我现在很难理解的是如何设计一个在运行时创建新对象的模型?我知道我的措辞可能是错误的,因为所有对象都是在运行时生成的,但是我的意思是,如果要在终端或UI中启动应用程序,我将如何创建和管理新对象.我真的不能即时定义新的变量名吗?
What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?
我遇到这个设计问题的示例应用程序是一个存储人员的数据库.用户将获得一个终端菜单,该菜单允许他创建一个新用户并分配姓名,薪水和职位.如果要管理对象,调用函数等,该如何实例化该对象并在以后调用它?这里的设计模式是什么?
An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?
请原谅我对OPP模型的理解不足.我目前正在阅读有关类和OOP的内容,但是我觉得在继续之前需要了解我的错误所在.请让我知道是否需要澄清.
Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.
推荐答案
列表或字典之类的东西对于存储动态生成的值/对象集非常有用:
Things like lists or dictionaries are great for storing dynamically generated sets of values/objects:
class Person(object):
def __init__(self, name):
self.name = name
def __repr__(self):
print "A person named %s" % self.name
people = {}
while True:
print "Enter a name:",
a_name = raw_input()
if a_name == 'done':
break
people[a_name] = Person(a_name)
print "I made a new Person object. The person's name is %s." % a_name
print repr(people)
这篇关于使用Python在运行时创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!