在尝试学习OOP概念时,我一直在努力的一件事就是创建类实例。在线上的大多数教程都将解释诸如Init,Self,Inheritance等的基本原理。但是,在创建类本身的实例时,通常将其简化为:
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属性来跟踪和“实例化”我的实例?教程是否有很好的资料来解决这个问题?
谢谢 雅各布
答案 0 :(得分:0)
在完成以下课程的教学后: https://pythonschool.net/category/oop.html ,我设法做到了:
Graph temp
用于测试以显示我所追求的简单主要功能:
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)