我想使用Python類和下面是我的第一個Python類代碼:Python類NameError:全局名稱沒有定義
import re
import time
import paramiko
hostname = "10.1.1.1"
net_username = "user"
net_password = "password"
class asr_qa:
def __init__(self, hostname, net_username, net_password):
''' SSH connection Establish '''
self.remote_conn_pre = paramiko.SSHClient()
self.remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
self.remote_conn_pre.connect(hostname, username=net_username,
password=net_password,look_for_keys=False, allow_agent=False)
self.remote_conn = remote_conn_pre.invoke_shell()
buff = ''
while not buff.endswith('#'):
resp = remote_conn.recv(9999)
buff += resp
print(resp)
def __disconnect__(self):
self.remote.close()
def __send_command__(self, cmd):
remote_conn.send(self.cmd)
asr = asr_qa(hostname, net_username, net_password)
asr.__send_command__("ping 10.10.10.10\n")
print asr.resp
asr.__disconnect__()
我得到以下錯誤:
Traceback (most recent call last):
File "test.py", line 30, in <module>
asr = asr_qa(hostname, net_username, net_password)
File "test.py", line 18, in __init__
self.remote_conn = remote_conn_pre.invoke_shell()
NameError: global name 'remote_conn_pre' is not defined
請讓我知道我做錯了什麼。
而且我試圖閱讀很多文檔,但我不明白__init__
究竟會做什麼。
__init__
是類的構造函數。當我們調用這個類時,它會初始化__init__
下的所有值(只要實例化該類的新對象,就會調用此特殊函數),並且爲什麼不能直接將__init__
值定義爲函數本身?
我們應該用什麼樣的情況__init__
由於您的錯誤所指出的,你還沒有定義'該代碼remote_conn_pre'任何地方,讓你的程序犯規認識到令牌。 – DarkCygnus
是否將'self.remote_conn = remote_conn_pre.invoke_shell()'更改爲'self.remote_conn = self.remote_conn_pre.invoke_shell()'更改錯誤? – brt
'remote_conn_pre'和'self.remote_conn_pre'是兩個不同的東西 –