То, что вы пытаетесь сделать, добавляя self
к переменной класса , является плохой практикой. Вам лучше выполнить следующее (хотя это также не «идеальная» практика):
item_list = []
class Item:
def __init__(self, x, y):
self.x = x
self.y = y
item_list.append(self)
def __str__(self):
return "x = " + str(self.x) + " / y = " + str(self.y)
a = Item(10,11)
for i in item_list:
print(i) # > x = 10 / y = 11
item_list.remove(a)
print(item_list) # > []
del a
Лучше было бы просто создать список и добавить элементы после их создания:
class Item:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "x = " + str(self.x) + " / y = " + str(self.y)
item_list = []
items = [(10, 11)]
for x, y in items:
item_list.append(Item(x, y))
for i in item_list:
print(i) # > x = 10 / y = 11
Вот способ OOP (объектно-ориентированное программирование) сделать это:
class Items:
def __init__(self):
self.items = []
def create_item(self, x, y):
if not isinstance(x, int) and not isinstance(y, int):
raise Exception("X and Y coordinates must be integers!")
elif Item(x, y) in self.items:
raise Exception("X and Y coordinates are already in the item list!")
self.items.append(Item(x, y))
def delete_item(self, x, y):
if Item(x, y) not in self.items:
raise Exception("X and Y coordinates given are not in item list!")
else:
self.items.remove(Item(x, y))
class Item:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if self.x == other.x and self.y == other.y:
return True
else:
return False
def __str__(self):
return "x = " + str(self.x) + " / y = " + str(self.y)
items = Items()
items.create_item(10, 11)
print("First:")
for item in items.items:
print(item)
items.create_item(15, 12)
items.delete_item(10, 11)
print("\nSecond:")
for item in items.items:
print(item)
вывод:
First:
x = 10 / y = 11
Second:
x = 15 / y = 12