[英]Is there a way to make multiple instances of a class in python
我正在开发一个用于自行车租赁服务的 GUI 应用程序,并且每次单击RENT A BIKE时都会创建一个class 客户的新实例。 以下是 GUI 的示例
import main
from BikeGUI.ADDSTOCK.add_stock import shp
#class which I want many instances of
customer = main.Customer()
#gui class
class Rent_Bike:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
#some gui definitions
top.geometry()
top.title()
...
...
...
...
#some more gui definitions
self.Label1 = tk.Label(top)
self.Label1.configure()
#more gui definitions
self.price = tk.Entry(top)
self.price.configure(text='''CodeName:''', .....)
...
...
...
#define tkinter variable
self.num_of_bikes = tk.StringVar()
self.Entry1.configure(insertbackground="black", textvariable=self.num_of_bikes)
...
...
...
def confirm_order(self):
#get number of bikes from entry
customer.bikes = self.num_of_bikes.get()
customer.rentalBasis = rent_bike_support.selected.get()
customer.codename = self.customername.get()
if __name__ == '__main__':
vp_start_gui()
那是 class 我希望客户 object 被实例化几次,但问题是它只被实例化一次,它会覆盖我之前创建的所有其他客户
PS 我稍后需要将此客户 object 导入另一个 GUI 文件这是我如何导入它
from BikeGUI.rentbike.rent_bike import customer
但我认为问题不在于将其导入另一个。 链接到我的文件
如果您的 class 被称为Rent_Bike
那么您使用instance = Rent_Bike()
对其进行实例化。 您可以根据需要多次执行此操作。 class 的一个实例称为 object。
如果您想在每次单击“租一辆自行车”按钮时创建客户 class 的新实例。 在Button
小部件中使用“command”参数并将其设置为 class 名称。
例如:如果您的 class 名称是foo
那么它应该是这样的: Button(root, text='Rent A Bike', command=foo)
。 如果您想将 append 每个新实例添加到列表中,请使用lambda
function 类似于此command=lambda:lst.append(foo())
。
下面是在同一文件中实例化 class 的示例:
from tkinter import *
import new_2
class Customer:
def __init__(self, root):
self.root = root
self.label = Label(self.root, text='Customer')
self.label.pack()
class foo:
def __init__(self):
print('Hello')
def print_lst():
print(lst)
root = Tk()
lst = []
btn = Button(root, text='Rent A Bike', command=lambda :lst.append(Customer(root)) or print_lst())
#btn = Button(root, text='Rent A Bike', command=lambda :lst.append(foo()) or print_lst())
btn.pack()
root.mainloop()
要在另一个文件中为 class 创建 object,只需导入该 class 并遵循与上述相同的过程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.