简体   繁体   中英

Struggling with Global Definition of Functions in python

I haven't used python in ages and I'm struggling with declaring and using a function. I am faced with a global name error when trying to call a function that I have defined.

I have tried using self but I am a little lost how this works.



def main(): 
    size = int(sys.argv[1])
    print(size)
    generate = gen(size)
    print(generate)

def gen(self, size):
    #generate...
    return size

if __name__ == "__main__":
        main()

The error I am faced with is NameError: global name 'gen' is not defined .

Just to answer the question directly-

class paging():
    def main(): 
        generate = gen(size)
    def gen(self, size):
        return size
  • The only thing in the global namespace here is paging which is a class.
  • Classes define methods- the global namespace of those methods is class.method . Therefore, the name of your function here should be paging.gen
  • instance methods (the functions you defined there) always take self as the first argument, which is a stand in for the instance of the class.
  • you can use the self to call other instance methods on the object ...

    def main(self): self.gen()

Keep at it, it can be hard to jump in cold

Seems like you don't need class here, if you want to run your code without the class, you can use

import random
import sys


def gen(size):
    # generate...
    return size

def main():
    #Not sure where you are passing pages?
    size = int(sys.argv[1])
    print(size)
    generate = gen(size)
    print(generate)
    print("FIFO", FIFO(size,pages), "page faults.")
    print("LRU", LRU(size,pages), "page faults")
    print ("OPT", OPT(size,pages), "page faults")

def FIFO(self, size, pages):
    return "hello"

def LRU(self, size, pages):
    return "hello"

def OPT(self, size, pages):
    return "hello"

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage: python paging.py [number of pages]"
    else:
        main()
  • replace this generate = gen(size) by generate = self.gen(size)
  • add self as the first argument of main method

You have to use the self. prefix if you're calling a method which is part of the class. If instead you want to call main() globally, and place it outside the class you should not define the main() and the gen() functions in the class it's self. so when you call gen() and gen() is not a global function but it's a function which is in the class you should type

generate = self.gen(size)

Remember that python indentation is the way to have blocks. So if you indent main, main will be in the class block, and it won't be available globally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM