在 Python 运行时创建对象

发布于 2024-10-12 18:26:12 字数 419 浏览 8 评论 0原文

当涉及到在运行时创建对象时,我在理解 OOP 概念时遇到了问题。我研究过的所有教育代码都定义了特定的变量,例如“Bob”,并将它们分配给一个新的对象实例。 Bob = Person()

我现在无法理解的是如何设计一个在运行时创建新对象的模型?我知道我的措辞可能有错误,因为所有对象都是在运行时生成的,但我的意思是,如果我要在终端或 UI 中启动我的应用程序,我将如何创建新对象并管理它们。我真的无法动态定义新的变量名称,对吗?

我遇到此设计问题的一个示例应用程序是存储人员的数据库。用户获得一个终端菜单,允许他创建新用户并分配姓名、工资、职位。如果您想管理它、调用函数等,您将如何实例化该对象并稍后调用它?这里的设计模式是什么?

请原谅我对 OPP 模型的理解不深。我目前正在阅读课程和 OOP,但我觉得在继续之前我需要了解我的错误是什么。如果有什么需要澄清的地方,请告诉我。

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()

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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

流心雨 2024-10-19 18:26:12

列表或字典之类的东西非常适合存储动态生成的值/对象集:

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)

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)
半世晨晓 2024-10-19 18:26:12

您不必使用变量名来存储每个对象。变量名称是为了方便程序员使用。

如果您想要对象的集合,您只需使用它 - 集合。使用包含对象实例的列表或字典,分别由索引或键引用。

例如,如果每个员工都有一个员工编号,您可以将它们保存在字典中,并以员工编号作为键。

You don't store each object with a variable name. Variable names are for the convenience of a programmer.

If you want a collection of objects, you use just that - a collection. Use either a list or a dictionary containing object instances, referenced by index or key respectively.

So for example, if each employee has an employee number, you might keep them in a dictionary with the employee number as a key.

夏日浅笑〃 2024-10-19 18:26:12

对于您的示例,您想要使用模型抽象。

如果 Person 是一个模型类,您可以简单地执行以下操作:

person = new Person()
person.name = "Bob"
person.email = "[email protected]"
person.save()  # this line will write to the persistent datastore (database, flat files, etc)

然后在另一个会话中,您可以:

person = Person.get_by_email("[email protected]") # assuming you had a classmethod called 'get_by_email'

For your example, you want to use a model abstraction.

If Person is a model class, you could simply do:

person = new Person()
person.name = "Bob"
person.email = "[email protected]"
person.save()  # this line will write to the persistent datastore (database, flat files, etc)

and then in another session, you could:

person = Person.get_by_email("[email protected]") # assuming you had a classmethod called 'get_by_email'
紫罗兰の梦幻 2024-10-19 18:26:12

我将尽力在这里回答:

  1. 您所问的是变量变量名 - 这不是 Python 中的。 (我认为它是在 VB.Net 中,但不要让我坚持这一点)

用户获得一个终端菜单,允许他创建新用户并分配姓名、薪水、职位。如果您想管理它、调用函数等,您将如何实例化该对象并稍后调用它?这里的设计模式是什么?

这就是我添加新人的方式(米老鼠示例):

# Looping until we get a "fin" message
while True:
    print "Enter name, or "fin" to finish:"
    new_name = raw_input()
    if new_name == "fin":
        break
    print "Enter salary:"
    new_salary = raw_input()
    print "Enter position:"
    new_pos = raw_input()

    # Dummy database - the insert method would post this customer to the database
    cnn = db.connect()
    insert(cnn, new_name, new_salary, new_pos)
    cnn.commit()
    cnn.close()

好的,现在您想从数据库中获取一个人。

while True:
    print "Enter name of employee, or "fin" to finish:"
    emp_name = raw_input()
    if emp_name == "fin":
        break
    # Like above, the "select_employee" would retreive someone from a database
    cnn = db.connect()
    person = select_employee(cnn, emp_name)
    cnn.close()

    # Person is now a variable, holding the person you specified:
    print(person.name)
    print(person.salary)
    print(person.position)

    # It's up to you from here what you want to do

这只是一个基本的、粗略的例子,但我想你明白我的意思了。

另外,正如您所看到的,我在这里没有使用类。类似这样的类几乎总是一个更好的主意,但这只是为了演示如何在运行时更改和使用变量。

I'll try to answer as best I can here:

  1. What you're asking about is variable variable names - this isn't in Python. (I think it's in VB.Net but don't hold me to that)

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?

This is how I'd add a new person (Mickey-mouse example):

# Looping until we get a "fin" message
while True:
    print "Enter name, or "fin" to finish:"
    new_name = raw_input()
    if new_name == "fin":
        break
    print "Enter salary:"
    new_salary = raw_input()
    print "Enter position:"
    new_pos = raw_input()

    # Dummy database - the insert method would post this customer to the database
    cnn = db.connect()
    insert(cnn, new_name, new_salary, new_pos)
    cnn.commit()
    cnn.close()

Ok, so you want to now get a person from the database.

while True:
    print "Enter name of employee, or "fin" to finish:"
    emp_name = raw_input()
    if emp_name == "fin":
        break
    # Like above, the "select_employee" would retreive someone from a database
    cnn = db.connect()
    person = select_employee(cnn, emp_name)
    cnn.close()

    # Person is now a variable, holding the person you specified:
    print(person.name)
    print(person.salary)
    print(person.position)

    # It's up to you from here what you want to do

This is just a basic, rough example, but I think you get what I mean.

Also, as you can see, I didn't use a class here. A class for something like this would pretty much always be a better idea, but this was just to demonstrate how you'd change and use a variable during runtime.

逆光飞翔i 2024-10-19 18:26:12

在真实的程序中你永远不会执行Bob = Person()。任何表明这一点的例子都可以说是一个坏例子;它本质上是硬编码。您将更频繁地(在实际代码中)执行 person = Person(id, name) 或类似的操作,使用您在其他地方获得的数据(从文件中读取、从用户交互接收)来构造对象, ETC。)。更好的是类似于employee = Person(id, name)

You would never do Bob = Person() in a real program. Any example that shows that is arguably a bad example; it is essentially hard-coding. You will more often (in real code) do person = Person(id, name) or something like that, to construct the object using data you obtained elsewhere (read from a file, received interactively from a user, etc.). Even better would be something like employee = Person(id, name).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文