calling a method inside a class-Python

Question:

class Time:

    def __init__(self,x,y,z):
        self.hour=x
        self.minute=y
        self.second=z

    def __str__(self):
        return "({:02d}:{:02d}:{:02d})".format(self.hour, self.minute, self.second)

    def time_to_int(time):
        minutes=time.hour*60+time.minute
        seconds=minutes*60+time.second
        return seconds

    def int_to_time(seconds):
        time=Time()
        minutes,time.second=divmod(seconds,60)
        time.hour,time.minute=divmod(minutes,60)
        return time

    def add_time(t1,t2):
        seconds=time_to_int(t1)+time_to_int(t2)
        return int_to_time(seconds)

start=Time(9,45,00)
running=Time(1,35,00)
done=add_time(start,running)
print(done)

I am new to python and i’ve been doing some practice lately.I came across a question and i’ve written the code for the same.But I am repeatedly getting an error: “add_time is not defined”. I tried defining a main() method but then it doesn’t print anything.Please help.

Asked By: mathers25

||

Answers:

You haven’t created an object to the above class.

Any function/method inside a class can only be accessed by an object of that class .For more information on the fundamentals of Object Oriented Programming, please check this page.

Meanwhile for this to work, define your class in the following way :

class Time:

def __init__(self,x=None,y=None,z=None):
    self.hour=x
    self.minute=y
    self.second=z

def __str__(self):
    return "({:02d}:{:02d}:{:02d})".format(self.hour, self.minute, self.second)

def time_to_int(time):
    minutes=time.hour*60+time.minute
    seconds=minutes*60+time.second
    return seconds

def int_to_time(seconds):
    time=Time()
    minutes,time.second=divmod(seconds,60)
    time.hour,time.minute=divmod(minutes,60)
    return time

def add_time(t1,t2):
    seconds=time_to_int(t1)+time_to_int(t2)
    return int_to_time(seconds)

and outside the class block, write the following lines :

TimeObject = Time()
start=Time(9,45,00)
running=Time(1,35,00)
TimeObject.add_time(start,running)
print "done"

I however suggest you to write the add_time function outside the class because you are passing the objects to the class as the parameters to the function within the same class and it is considered as a bad design in object oriented programming.
Hope it helps. Cheers!

Answered By: crazyglasses

Works for me:

class C:
  def f(a, b):
    return a + b
  x = f(1,2)

print(C.x)

but you should not do such things. Code in class-level is executing when class is “creating”, usually you want static methods or class methods (decorated with @staticmethod or @classmethod) and execute code in some function/instantiated class. Also you can execute it on top (module) level if this is the simple script. Your snippet is “bad practice”: class level (i’m talking about indentation) is for declarations, not for execution of something. On class-level is normal to execute code which is analogue of C macros: for example, to call decorator, to transform some method/attribute/etc – static things which are “pure” functions!

Answered By: RandomB

This works fine for me as long as you specified 3 args in your constructor

def int_to_time(seconds):
    time=Time(0,0,0) # just set your 3 positionals args here
    minutes,time.second=divmod(seconds,60)
    time.hour,time.minute=divmod(minutes,60)
    return time

Another way to avoid it could be:

class Time:
    def __init__(self,x=0,y=0,z=0):
        self.hour=x
        self.minute=y
        self.second=z

If you want to add your functions to your class (such as time_to_int, int_to_time or even add_time) then you will need to indent with one more level of 4 spaces and add self to your method parameters

Answered By: pBouillon

Hii Mathers25,
I solve your problem try this below code to get the best output,

class TimeClass:

def __init__(self,x,y,z):
    self.hour = x
    self.minute = y
    self.second = z

def __str__(self):
    return "({:02d}:{:02d}:{:02d})".format(self.hour, self.minute, self.second)

def time_to_int(self,time):

    minutes = (time.hour * 60) + time.minute
    seconds = (minutes * 60) + time.second
    return seconds

def int_to_time(self,seconds):
    time = TimeClass(0,0,0)
        minutes,time.second=divmod(seconds,60)
        time.hour,time.minute=divmod(minutes,60)
        return time

def add_time(self,t1,t2):
    seconds = self.time_to_int(t1) + self.time_to_int(t2)
    # Call method int_to_time() using self keyword.
    return self.int_to_time(seconds)


# First time object create that time set value is 0 of hour,minute and second
TimeObject = TimeClass(0,0,0)

# After create second object
start=TimeClass(9,45,00)

# After create thired Object
running=TimeClass(1,35,00)

# Store the value which return by add_time() 
done = TimeObject.add_time(start,running)

# Display the value of done variable
print(done)
Answered By: Er CEO Vora Mayur
class Employee:
    def __init__(self):
        self.wage = 0
        self.hours_worked = 0

    def calculate_pay(self):
        return self.wage * self.hours_worked

alice = Employee()
alice.wage = 9.25
alice.hours_worked = 35
print('Alice:n Net pay: {:.2f}'.format(alice.calculate_pay()))

barbara = Employee()
barbara.wage = 11.50
barbara.hours_worked = 20
print('Barbara:n Net pay: {:.2f}'.format(barbara.calculate_pay()))
Answered By: Alfredo Romero
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.