Search code examples
pythonclasspython-2.7class-method

How to use functions inside @classmethod decorator


When using @classmethod this is passed first instead of self. Now inside the method with this decorator i need to call functions that are not defined inside this decorator but are defined in the class. How can i call the two functions get_int_input and get_non_int_input so that i can pass them to the return cls(name,pay_rate,hours) statement?

class Employee(object):

    def __init__(self,name,pay_rate,hours):        
        self.name = name
        self.pay_rate = pay_rate
        self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")

    def get_int_input(prompt):
        while True:
            pay_grade = raw_input(prompt)
            try:
                i = int(pay_grade)
            except ValueError:
                print "Int Only"
            else:
                return i

    def get_non_int_input(prompt):
        while True:
            a_name = raw_input(prompt)
            try:
                i = int(a_name)
            except ValueError:
                return a_name
            else:
                print " Strings Only"

    @classmethod
    def from_input(cls):

        day_count = 1
        hours = ("m","tue","w","thur","f","s","sun")
        while day_count <= 7:
            for day in hours:
                day = input("  Enter hours for day " + str(day_count) + "--- ")
                day_count += 1     


        return cls(name,pay_rate,hours)
     name = get_non_int_input("\n  Enter new employee name\n")
     pay_rate = get_int_input("Enter pay rate  ")


employee = Employee.from_input()
print str(employee)

Solution

  • You would add the @staticmethod decorator before the other two classes. Since they don't take either the Employee class or one of its instances as their first argument, they operate independently of a particular class or instance, and in this sense are "static".

    A method decorated in this manner is an attribute of its containing class, and is called as a class attribute, for example:

    >>> class Foo(object):
    ...     @staticmethod
    ...     def bar():
    ...         print 'called the static method'
    ... 
    >>> Foo.bar()
    called the static method
    

    This works the same way if you're calling Foo.bar() from inside one of Foo's class methods.

    There are some other problems here, though - I would advise you to seek more comprehensive review and advice.