Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a class method from within that class

Is there a way to call a class method from another method within the same class?

For example:

+classMethodA{ }  +classMethodB{     //I would like to call classMethodA here } 
like image 563
prostock Avatar asked Sep 02 '11 23:09

prostock


People also ask

How do you call a class method within a class in Python?

To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.

How do you call a class method?

To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.

Can we call method inside method in Python?

In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems.

How do you call a method from an instance of a class?

To call an object's method, you must use the object name and the dot (.) operator followed by the method name, for example object.


1 Answers

In a class method, self refers to the class being messaged. So from within another class method (say classMethodB), use:

+ (void)classMethodB {     // ...     [self classMethodA];     // ... } 

From within an instance method (say instanceMethodB), use:

- (void)instanceMethodB {     // ...     [[self class] classMethodA];     // ... } 

Note that neither presumes which class you are messaging. The actual class may be a subclass.

like image 141
Jon Reid Avatar answered Oct 08 '22 11:10

Jon Reid