我在学习OOP概念时遇到的一件事就是创建类实例。大多数在线教程将解释基本原理,如初始化、自我、继承等。但当涉及到创建类本身的实例时,通常会简化为如下所示:
emp1 = Employee("John")
emp2 = Employee("Leviticus")
实际上,我们大多数初学者都希望动态创建类的实例(按下按钮等)。不会直接在代码中使用,也会对跟踪我们的实例很感兴趣。我能想到的是:
from tkinter import *
import random
class Point:
_registry = []
def __init__(self, x_pos, y_pos):
self._registry.append(self)
self.x_pos = x_pos
self.y_pos = y_pos
print(self.x_pos, self.y_pos)
def create_point():
Point(random.randint(1,20),random.randint(1,20))
window = Tk()
button = Button(window, text = "Add point", command=create_point)
button.pack()
window.mainloop()
有人能建议一下这是不是一种合适的方式?函数create_point不应该在Point类中吗?跟踪实例并在以后删除它们的正确方法是什么?我是否应该使用某种ID属性来跟踪和“逐条列出”我的实例?有没有什么好的教程可以解决这个问题呢?
谢谢雅各布
发布于 2018-07-19 07:00:06
在上完成教程后,我设法通过执行以下操作获得了我想要的:
class Point:
def __init__(self,ID, xcor, ycor):
self._ID = ID
self._xcor = xcor
self._ycor = ycor
def report(self):
return {"ID:":self._ID,"xcor":self._xcor,"ycor":self._ycor}
def get_ID(self):
return self._ID
class Points:
def __init__(self):
self._points = []
def add_point(self, point):
self._points.append(point)
def return_index_from_ID(self, ID):
for i, o in enumerate(self._points):
if o.get_ID() == ID:
break
return i
def delete_point(self, index):
del self._points[index]
def print_contents(self):
for x in self._points:
print(x.report())
def return_empty_ID(self):
list = []
for x in self._points:
list.append(x.get_ID())
if not list:
return 1
else:
for i in range(1, max(list)+2):
if i not in list: break
return i
def add_point( xcor, ycor, points):
points.add_point(Point(points.return_empty_ID(), xcor, ycor))
def delete_point(ID, points):
points.delete_point(ID)
简单的main函数用于测试,以显示我想要的内容:
from point_class import *
myPoints = Points()
noexit = True
while noexit:
print("**********************************************")
print("0 - Exit")
print("1 - Add Point")
print("2 - Print Points")
print("3 - Delete Points")
print("**********************************************")
choice = int(input("Option selected: "))
if choice == 0:
noexit = False
elif choice == 1:
add_point(3,5,myPoints)
elif choice == 2:
myPoints.print_contents()
elif choice == 3:
ID = int(input("Please insert ID of point: "))
delete_point(myPoints.return_index_from_ID(ID),myPoints)
https://stackoverflow.com/questions/51390918
复制相似问题