How to use functions inside @classmethod decorator
当使用@classmethod时,它将首先传递而不是self。现在,在使用这个修饰器的方法中,我需要调用那些没有在这个修饰器中定义但在类中定义的函数。如何调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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(" Enter new employee name ") pay_rate = get_int_input("Enter pay rate ") employee = Employee.from_input() print str(employee) |
您可以在其他两个类之前添加
以这种方式修饰的方法是其包含类的属性,并作为类属性调用,例如:
1 2 3 4 5 6 7 | >>> class Foo(object): ... @staticmethod ... def bar(): ... print 'called the static method' ... >>> Foo.bar() called the static method |
如果您从
不过,这里还有一些其他问题——我建议您寻求更全面的审查和建议。
您在
用
您似乎缺少一些编程的核心概念
您可能应该在Google中查找名称空间和范围。
你可能不应该和约翰·R·夏普谈,因为他很有帮助,我冒昧地猜测,如果你继续编程,你会遇到更多的问题,你会因此而来寻求帮助。
这里说的都是你的固定密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #first pull these two functions out of your class they have nothing to do with employee #they should just be normal functions # #... if you wanted to make them part of a class make an input class and add them as static methods to that 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" 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") @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 #name and pay_rate must be defined prior to using them in your return function ... name = get_non_int_input(" Enter new employee name ") pay_rate = get_int_input("Enter pay rate ") #now that you have all the info just return it return cls(name,pay_rate,hours) employee = Employee.from_input() print str(employee) |