![](/img/trans.png)
[英]Python access to objects created by Java-Application during runtime
[英]Creating objects during runtime in Python
在運行時創建對象時,我有一個掌握OOP概念的問題。 我所研究的所有教育代碼都定義了特定的變量,例如'Bob',並將它們分配給一個新的對象實例。 Bob = Person()
我現在理解的是如何設計一個在運行時創建新對象的模型? 我知道我的短語可能有問題,因為所有對象都是在運行時生成的,但我的意思是,如果我要在終端或UI中啟動我的應用程序,我將如何創建新對象並對其進行管理。 我不能真正定義新的變量名稱嗎?
我遇到這個設計問題的一個示例應用程序是存儲人員的數據庫。 用戶獲得終端菜單,允許他創建新用戶並分配姓名,工資,職位。 如果你想管理它,調用函數等,你將如何實例化該對象並稍后調用它? 這里的設計模式是什么?
請原諒我對OPP模型的不了解。 我正在閱讀課程和OOP,但我覺得在繼續學習之前我需要了解我的錯誤。 如果有任何我需要澄清的內容,請告訴我。
列表或詞典之類的東西非常適合存儲動態生成的值/對象集:
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)
您不會使用變量名存儲每個對象。 變量名稱是為了方便程序員。
如果你想要一個對象集合,你只需使用它 - 一個集合。 使用包含對象實例的列表或字典,分別由索引或鍵引用。
因此,例如,如果每個員工都有員工編號,您可以將他們保存在字典中,並將員工編號作為密鑰。
對於您的示例,您希望使用模型抽象。
如果Person
是模型類,您可以簡單地執行:
person = new Person()
person.name = "Bob"
person.email = "bob@aol.com"
person.save() # this line will write to the persistent datastore (database, flat files, etc)
然后在另一個會話中,您可以:
person = Person.get_by_email("bob@aol.com") # assuming you had a classmethod called 'get_by_email'
我會盡力回答:
用戶獲得終端菜單,允許他創建新用戶並分配姓名,工資,職位。 如果你想管理它,調用函數等,你將如何實例化該對象並稍后調用它? 這里的設計模式是什么?
這是我添加新人的方式(米老鼠示例):
# 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
這只是一個基本的,粗略的例子,但我認為你理解我的意思。
另外,正如你所看到的,我沒有在這里使用課程。 類似這樣的類幾乎總是一個更好的主意,但這只是為了演示如何在運行時更改和使用變量。
你永遠不會在一個真實的程序中做Bob = Person()
。 任何顯示這可能是一個壞例子的例子; 它本質上是硬編碼。 您將更頻繁地(在實際代碼中)執行person = Person(id, name)
或類似的事情,使用您在其他地方獲得的數據構建對象(從文件中讀取,從用戶交互接收等)。 更好的是像employee = Person(id, name)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.