如何在函式中呼叫變數:
什么是正確的方法:
- 應該在之前定義變數班級要么
- 我們可以在下面定義它班級要么功能
示例代碼:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
timeStamp = time.strftime("%Y%m%d%H%M%S") # <-- Is this right Approach
class Scanner:
INFO = 0
DEBUG = 3
timeStamp = time.strftime("%Y%m%d%H%M%S") # <-- ?
def __init__(self, config_file, verbose=False):
""" Constructor """
def ask_passwords(self):
def ldap_init(self):
def hosts_module_scanner(self):
def users_module_scanner(self):
def ldap_reporting(self, user_list):
self.write_report(failed_users, "users_ldap_report-{}.txt".format(timeStamp))
def option_parser(prog_version):
if __name__ == '__main__':
scanner.ask_passwords()
scanner.ldap_init()
scanner.hosts_module_scanner()
scanner.users_module_scanner()
注意:在上面的示例中,如果我在class.
uj5u.com熱心網友回復:
您可以使用以下語法在類中呼叫變數: self.variable_name = # 無論您分配變數。
至于課堂上的位置,最好的選擇是在 def init _() 位內。
編輯:作為更詳細的答案。您將在init方法中定義變數,如下所示。在類中使用 self.variable,但在方法(類函式)之外使用會拋出“self is not defined”錯誤。
class Scanner:
def __init__(self, config_file, verbose=False):
""" Constructor """
self.INFO = 0
self.DEBUG = 3
self.timeStamp = time.strftime("%Y%m%d%H%M%S")
#declare rest of variables here
#other class methods go here
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438965.html
標籤:python-3.x 功能 全局变量
