tyvm
tyvm

Reputation: 111

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.

Upvotes: 0

Views: 77

Answers (4)

benjamin
benjamin

Reputation: 77

  • replace this generate = gen(size) by generate = self.gen(size)
  • add self as the first argument of main method

Upvotes: 0

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

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()

Upvotes: 1

Paul Iyobo
Paul Iyobo

Reputation: 54

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.

Upvotes: 0

Paul Becotte
Paul Becotte

Reputation: 9977

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

Upvotes: 1

Related Questions