[英]Calling an instance variable from a class that is inside of that class
我有一個具有logger實例變量的類,我正在創建另一個類,我想在該類中使用logger實例變量,但不知道如何調用它。
示例代碼:
class A():
def __init__(self):
self.logger = Logger.get() #this works fine didn't include the Logger class
def func(self):
class B():
def __init__(self):
self.a = 'hello'
def log(self):
#How do I call A's logger to log B's self.a
#I tried self.logger, but that looks inside of the B Class
正如Python的Zen所說, “Flat比嵌套更好”。 您可以取消嵌套B
,並將記錄器作為參數傳遞給B.__init__
。 通過這樣做,
B
依賴的變量。 B
變得更容易進行單元測試 B
可以在其他情況下重復使用。 class A():
def __init__(self):
self.logger = Logger.get() #this works fine didn't include the Logger class
def log(self):
b = B(self.logger)
class B():
def __init__(self, logger): # pass the logger when instantiating B
self.a = 'hello'
self
名稱不是語言要求,它只是一種慣例。 您可以使用不同的變量名稱,如a_self
因此外部變量不會被屏蔽。
class A():
def __init__(self):
self.logger = Logger.get() #this works fine didn't include the Logger class
def func(a_self):
class B():
def __init__(self):
self.a = 'hello'
def log(self):
a_self.logger.log('...')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.