Search code examples
python-3.xfunctionglobal-variables

How to call a variable within a function if it runs under a Class


How to call a variable within a function:

What is the Right approach:

Sample Code:

#!/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()

Note: In the above example it doesn't work if i define under class.


Solution

  • You can call variables within a class, using the syntax: self.variable_name = # whatever you're assigning the variable.

    As for where abouts in the class, your best bet is within the def init_() bit.

    edit: As a more verbose answer. you'll define the variables in the init method as shown below. Using self.variable in a class, but outside the methods (class functions) will throw a "self is not defined" error.

    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