Python 从另一个类访问内部属性
如果我有以下两门课:Python 从另一个类访问内部属性,python,Python,如果我有以下两门课: class Test() def __init__(self): self._path={} # key= source node, value = list of neighbors class PrintNodes() def printing(self) Test()._path[key] # Is it possible? 如果要在自已.java路径{{} >从 PrtNoSdEd()/Cux>类中循环,我需要用与Jav
class Test()
def __init__(self):
self._path={} # key= source node, value = list of neighbors
class PrintNodes()
def printing(self)
Test()._path[key] # Is it possible?
如果要在非常感谢。如果希望PrintNodes能够访问测试实例的属性,则需要将测试实例传递给PrintNodes实例 例如:
class Test()
def __init__(self):
self._path={}
Class PrintNodes()
def printing(self, test) # pass in the instance here
print(test._path[key])
Python没有强大的访问保护机制,如C++或Java,因此没有任何好处标记测试的代码> java路径< /代码>属性为私有的,除非它是其他类依赖的危险。因此,您的代码可以如下所示:
class Test()
def __init__(self):
self.path={} # not private
Class PrintNodes()
def printing(self, test)
print(test.path[key])
如果依赖路径是危险的-例如,将来您可能会将路径从
dict
更改为list
,然后使用前导下划线将其标记为private,并避免在其他类中访问它。您是否尝试过您的代码?实际上,没有,我只是想了解一些想法。我现在就做。谢谢您,您的代码应该可以工作。snakecharmerb是正确的,但您的代码也可以工作。我以为他在问一些关于抽象类的问题。就像调用抽象方法一样