简体   繁体   中英

How to def a function inside a Class

So guys, sorry if this question posted again. i dont know, why convert_int() is undefined even i've defined it. please reply this if you can answer. Thank you guys:)

class Abc(object):
    def __init__(self,words):
        self.words = words
    def convert_int(s): #here the problem, @staticmethod can't solve this
        try:
            return int(s)

        except ValueError:
            return s
    def test(self):
        words = self.words
        words = convert_int(words)
        return words

f = Abc("12345")
print(f.test())

You have used convert_int as for an instance method in the class.

class Abc(object):
    def __init__(self,words):
        self.words = words

    def convert_int(self, s): #updated
        try:
            return int(s)
        except ValueError:
            return s
    def test(self):
        words = self.words
        words = self.convert_int(words) #updated
       return words
f = Abc("12345")
print(f.test())

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