![](/img/trans.png)
[英]How to get the name of the instance of the parent class from the derived class in Python?
[英]How to get name of instance from class in for loop
我有一個添加到列表的類的多個實例。 我遍歷該列表,檢查一些條件。 在這些條件下,我從列表中選擇某些對象並將其添加到新列表中。 因為這些對象來自類,所以新列表的內容是該類中對象的內存分配。 我希望獲得實例的原始名稱。
老實說,我不知道為什么會這樣,我還沒有找到解決問題的答案,也許我在某個地方犯了錯誤,或者我只是不知道。 請發表答案
class Node():
def __init__(self, y, x):
self.y = y
self.x = x
def operation(self):
return x**2
node1 = Node(2,2)
node2 = Node(3,3)
nodes = [node1, node2]
for node in nodes:
good_nodes = []
if ##CONDITIONS##:
##select certain nodes##
else:
good_nodes.append(##selected_nodes##, for example : node1)
print(good_nodes)
返回什么: [<__main__.Node object at 0x7fe608b27668>]
我要返回的內容(列表): [node1,node2,etc]
名稱與值相關聯。 值不知道引用它的名稱。 這意味着您無法從值中獲取變量名稱。
如果要打印出有意義的方式來標識節點,則可以覆蓋__str__()
。 例如:
class Node:
# existing code
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
如果要每個節點都有一個名稱,則必須自己添加:
class Node:
def __init__(self, y, x, name):
self.y = y
self.x = x
self.name = name
為了打印出來,您必須在第一個示例中修改__str__()
函數。
如果要稍后通過名稱標識Node的實例,最佳做法是向該對象添加名稱屬性。 使用變量名通常不是一個好主意,因為它們所指的內容可能會更改。
class Node():
def __init__(self, name, y, x):
self.name = name
self.y = y
self.x = x
def operation(self):
return x**2
def __repr__(self):
return self.name
node1 = Node('node1', 2, 2)
node2 = Node('node2', 2, 2)
In [0]: print([node1,node2])
Out [0]:
[node1, node2]
您似乎想要訪問在代碼的一部分,在代碼的完全不同的部分中引用對象的變量的名稱。 不幸的是,這不是Python的工作方式。
名稱node1
和node2
僅在該代碼塊中有意義,並且如果在不同代碼塊中引用了同一對象,則不能進行反向工程。 如果兩個代碼塊為同一對象使用不同的名稱,則將導致問題。 哪一個是“真實”的? 如果您希望他們使用規范名稱,則必須給他們一個名字,就像其他答案所建議的那樣。
我還要指出,您的代碼中有一個錯誤:
...
for node in nodes:
good_nodes = [] ## BUG HERE ##
if ##CONDITIONS##:
##select certain nodes##
else:
good_nodes.append(##selected_nodes##, for example : node1)
...
這里的每個循環都會覆蓋good_nodes
,因此您將只打印最后一個“好節點”。 您需要將行移動到循環之外:
...
nodes = [node1, node2]
good_nodes = [] # Much better!
for node in nodes:
if ##CONDITIONS##:
##select certain nodes##
else:
good_nodes.append(##selected_nodes##, for example : node1)
print(good_nodes)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.