Python calling method from class

calling a method inside a class-Python

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.

Please fix your indentation. Are time_to_int and so on supposed to be standalone functions, or methods of the class? If the former, they need to be dedented outside the class definition.

5 Answers 5

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 "(::)".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!

No. start and running are objects of your class time. To access the add_time method of the class Time, you need another object and hence I have created a TimeObject just to access the add_time method. However I suggest you make the add_time method independant and rest can be within the class.

Sorry I missed that, now I have edited so I can initialize it without having to pass it any parameter.

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 "(::)".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) 

Источник

Читайте также:  Php массив переменных функции

Call Class Method From Another Class

Is there a way to call the method of a class from another class? I am looking for something like PHP’s call_user_func_array() . Here is what I want to happen:

class A: def method1(arg1, arg2): . class B: A.method1(1, 2) 

Does that really need to be a class method and not a function? Static methods in other languages don’t necessarily map to a class method in Python. Give this a read: dirtsimple.org/2004/12/python-is-not-java.html

@Ivo Honestly, what do you care if he writes his own MVC before he learns the basics? let him try and learn the basics in the process. quit being so condescending to people asking questions.

5 Answers 5

update: Just saw the reference to call_user_func_array in your post. that’s different. use getattr to get the function object and then call it with your arguments

class A(object): def method1(self, a, b, c): # foo method = A.method1 

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A .

a = A() method = a.method1 method(1, 2) 

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1 : you will no longer be able to reference self in method1 but you will get passed a cls instance in it’s place which is A in this case.
  3. apply the staticmethod decorator to method1 : you will no longer be able to reference self , or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super .
class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up def method1(self, a, b): return a + b @staticmethod def method2(a, b): return a + b @classmethod def method3(cls, a, b): return cls.method2(a, b) t = Test1() # same as doing it in another class Test1.method1(t, 1, 2) #form one of calling a method on an instance t.method1(1, 2) # form two (the common one) essentially reduces to form one Test1.method2(1, 2) #the static method can be called with just arguments t.method2(1, 2) # on an instance or the class Test1.method3(1, 2) # ditto for the class method. It will have access to the class t.method3(1, 2) # that it's called on (the subclass if called on a subclass) # but will not have access to the instance it's called on # (if it is called on an instance) 

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Читайте также:  Магический метод add питон

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

Источник

Python calling method in class

I’m punching way above my weight here, but please bear with this Python amateur. I’m a PHP developer by trade and I’ve hardly touched this language before. What I’m trying to do is call a method in a class. sounds simple enough? I’m utterly baffled about what ‘self’ refers to, and what is the correct procedure to call such a method inside a class and outside a class. Could someone explain to me, how to call the move method with the variable RIGHT . I’ve tried researching this on several ‘learn python’ sites and searches on StackOverflow, but to no avail. Any help will be appreciated. The following class works in Scott’s Python script which is accessed by a terminal GUI (urwid). The function I’m working with is a Scott Weston’s missile launcher Python script, which I’m trying to hook into a PHP web-server.

class MissileDevice: INITA = (85, 83, 66, 67, 0, 0, 4, 0) INITB = (85, 83, 66, 67, 0, 64, 2, 0) CMDFILL = ( 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) STOP = ( 0, 0, 0, 0, 0, 0) LEFT = ( 0, 1, 0, 0, 0, 0) RIGHT = ( 0, 0, 1, 0, 0, 0) UP = ( 0, 0, 0, 1, 0, 0) DOWN = ( 0, 0, 0, 0, 1, 0) LEFTUP = ( 0, 1, 0, 1, 0, 0) RIGHTUP = ( 0, 0, 1, 1, 0, 0) LEFTDOWN = ( 0, 1, 0, 0, 1, 0) RIGHTDOWN = ( 0, 0, 1, 0, 1, 0) FIRE = ( 0, 0, 0, 0, 0, 1) def __init__(self, battery): try: self.dev=UsbDevice(0x1130, 0x0202, battery) self.dev.open() self.dev.handle.reset() except NoMissilesError, e: raise NoMissilesError() def move(self, direction): self.dev.handle.controlMsg(0x21, 0x09, self.INITA, 0x02, 0x01) self.dev.handle.controlMsg(0x21, 0x09, self.INITB, 0x02, 0x01) self.dev.handle.controlMsg(0x21, 0x09, direction+self.CMDFILL, 0x02, 0x01) 

Источник

Читайте также:  Html mail mime type

Python using methods from other classes

If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don’t have to rewrite my function?

3 Answers 3

  • instanciate an object in your class, then call the desired method on it
  • use @classmethod to turn a function into a class method
class A(object): def a1(self): """ This is an instance method. """ print "Hello from an instance of A" @classmethod def a2(cls): """ This a classmethod. """ print "Hello from class A" class B(object): def b1(self): print A().a1() # => prints 'Hello from an instance of A' print A.a2() # => 'Hello from class A' 

Or use inheritance, if appropriate:

class A(object): def a1(self): print "Hello from Superclass" class B(A): pass B().a1() # => prints 'Hello from Superclass' 

There is no multiple inheritance here. This is single inheritance, although it is possible that you are thinking of hierarchical inheritance.

There are several approaches:

The following examples use each for sharing a function that prints a member.

class Common(object): def __init__(self,x): self.x = x def sharedMethod(self): print self.x class Alpha(Common): def __init__(self): Common.__init__(self,"Alpha") class Bravo(Common): def __init__(self): Common.__init__(self,"Bravo") 
class Common(object): def __init__(self,x): self.x = x def sharedMethod(self): print self.x class Alpha(object): def __init__(self): self.common = Common("Alpha") def sharedMethod(self): self.common.sharedMethod() class Bravo(object): def __init__(self): self.common = Common("Bravo") def sharedMethod(self): self.common.sharedMethod() 

Super-sneaky Delegation
This solution is based off of the fact that there is nothing special about Python member functions; you can use any function or callable object so long as the first parameter is interpreted as the instance of the class.

def commonPrint(self): print self.x class Alpha(object): def __init__(self): self.x = "Alpha" sharedMethod = commonPrint class Bravo(object): def __init__(self): self.x = "Bravo" sharedMethod = commonPrint 

Or, a similarly sneaky way of achieving delegation is to use a callable object:

class Printable(object): def __init__(self,x): self.x = x def __call__(self): print self.x class Alpha(object): def __init__(self): self.sharedMethod = Printable("Alpha") class Bravo(object): def __init__(self): self.sharedMethod = Printable("Bravo") 

Источник

Оцените статью