lorenzoid
lorenzoid

Reputation: 1832

Calling a method inside of init function python

I'm having an issue with this code:

import math

class Money(object):

    def __init__(self, salary):
        self.salary = salary
        sal(self.salary)

    def sal(self, x):
        y = ( x - ( ( (x * 0.22) + 6534) ) -  (1900.9408 + ( (x - 37568)*.077) ) )
        print '-----------------------------------------------------------'
        print 'monthly income before tax will be: ${0:.2f}' .format(x/12)
        print 'bi-weekly income before tax will be: ${0:.2f}' .format(x/24)
        print 'Hourly after tax: ${0:.2f}' .format(x/24/70)
        print '-----------------------------------------------------------'
        print 'Income after tax will be: ${0:.2f}' .format(y)
        print 'Monthly after tax: ${0:.2f}' .format((y/12))
        print 'bi-weekly after tax:  ${0:.2f}' .format((y/24))
        print 'Hourly after tax: ${0:.2f}' .format(y/24/70)


        answer = raw_input('Do you want to do this again?\nType [Y] or [N]: ')
        if( answer == 'Y'):
            sal(x)
        else:
            print 'Thank you!'
            return


def main():

    x = input('Enter your taxable income: ')
    salaryLister = Money(x)

main()

The traceback shows this:

Traceback (most recent call last):
  File "taxableincome.py", line 35, in <module>
    main()
  File "taxableincome.py", line 33, in main
    salaryLister = Money(x)
  File "taxableincome.py", line 7, in __init__
    sal(self.salary)
NameError: global name 'sal' is not defined

What does: global name 'sal' is not defined mean?

Feel free to make comments about my design as well. I'd love to learn.

Upvotes: 1

Views: 5222

Answers (1)

Ahmed Aeon Axan
Ahmed Aeon Axan

Reputation: 2139

use self.sal, this is how you call instance methods of classes in python

How this works in python is, If you look at the method signature you have

def sal(self, salary)

basically, it needs the class reference as the first variable. And in python when you do self.sal it translates to

Money.sal(self, salary)

You can also call the method like this, but the recommended way is

self.sal(salary)

As per comments on your code, There definitely aren't any clear red flags. Though the last return statement in the sal function is not required. Its not a problem having it there, just something that caught my eye.

Also since you asked, I'd like to point this out. Please try to keep to a coding standard. let it be your own or someone else's. The important thing is consistency. But PEP-8 is generally the accepted style for python. You even have plugins for your editor which help you stick to it. You might want to read the style guide linked here.

Upvotes: 2

Related Questions