Home > database >  When I declare a function inside a class I get name error
When I declare a function inside a class I get name error

Time:11-30

The first code work properly but when I declare the 'toStr' function(or method) inside the class I get error. What's wrong with this code? First Code:

class Test:
    def __init__(self,hour,minute,second):
        self.hour=hour
        self.minute=minute
        self.second=second

# Return String Time Format
def toStr(self):
    return str(self.hour) ":" str(self.minute) ":" str(self.second)
t=Test(10,20,50)
print(toStr(t))

The second code with NameError:

class Test:
    def __init__(self,hour,minute,second):
        self.hour=hour
        self.minute=minute
        self.second=second

# Return String Time Format
    def toStr(self):
        return str(self.hour) ":" str(self.minute) ":" str(self.second)
t=Test(10,20,50)
print(toStr(t))

CodePudding user response:

Here is my code,

class Test:
    def __init__(self,hour,minute,second):
        self.hour=hour
        self.minute=minute
        self.second=second

# Return String Time Format
    def toStr(self):
        return str(self.hour) ":" str(self.minute) ":" str(self.second)

t=Test(10,20,50)
print(t.toStr())

here is my output,

10:20:50

You can't call the toStr function outside the t object (Test class), you need to call it using the dot operator because the toStr function belongs to the Test class now.

CodePudding user response:

You need to either call the method on the object like:

print(t.toStr())

or

print(Test.toStr(t))

CodePudding user response:

-> As you are working with object-oriented concepts. you should be familiar with it. whenever you create a class you have to create object of it to use its functionality

class MyTest: #class
    def __init__(self, hour, minute, second): #constructor
        self.hour=hour
        self.minute=minute
        self.second=second

    def toStr(self): #method
        return str(self.hour) ":" str(self.minute) ":" str(self.second)

obj=MyTest(4,5,5) # class object
print(obj.toStr()) # to call toStr() method you have to use it with a object.
  • Related