Call Class Method From Another Class
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
- Use an instance of
A
to callmethod1
(using two possible forms) - apply the
classmethod
decorator tomethod1
: you will no longer be able to referenceself
inmethod1
but you will get passed acls
instance in it's place which isA
in this case. - apply the
staticmethod
decorator tomethod1
: you will no longer be able to referenceself
, orcls
instaticmethod1
but you can hardcode references toA
into it, though obviously, these references will be inherited by all subclasses ofA
unless they specifically overridemethod1
and do not callsuper
.
Some examples:
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.
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.
Can't call method from another class in Java
You have to do something like below:
public class Persona {
...
//You should have instance of RegistroCompra
RegistroCompra registraCompra = new RegistroCompra();
public void setDestino() {
//Option 1: Explicitly call the method
registraCompra.seleccionarDestino();
destinoPasajero = registraCompra.obtenerDestino();
}
}
public class RegistroCompra {
private String destino;
public RegistroCompra(){
//Option 2 : Call the method in constructor
registraCompra();
}
public void seleccionarDestino() {
...
//Set the input to the class level variable destino
this.destino = input.nextLine();
}
public String obtenerDestino() {
return this.destino;
}
}
How to call a method function from another class in Javascript
A class is nothing more than a generic definition of an object. You cannot call class methods from the classes themselves. You need to instantiate an object from that class, then you would be able to call the class methods on the object.
class B {
method2() {
console.log("method2 in objectB called");
}
}
class A {
method1() {
console.log("method1 in objectA called");
var objB = new B();
objB.method2();
}
constructor() {
//some code
}
render() {
console.log("render in objectA called");
}
}
var objectA = new A();
var objectB = new B();
objectA.method1();
objectA.render();
Call method from another class without inheritance and creating an instance
The self
in _build_record(self)
should be its class's own instance. But it's expecting some other class's instance so this all looks confusing.
Python provides two ways to call methods of class without creating instance: classmethod
and staticmethod
.
Your examples looks like a good use case for staticmethod
.
class helper(object):
@staticmethod
def _build_record(person):
return { 'name': person.name, 'age': person.age }
Now it's more clear that _build_record
expects a person instance.
Update:
If you want to have access to the class (so that you can call its other methods), you should use classmethod
. A classmethod
will receive the current class as the first argument.
class helper(object):
@classmethod
def _build_record(cls, person):
# now you can call other methods of the class
cls.some_other_method()
return ...
classmethod
and staticmethod
are called in the same manner.
Java: How to access methods from another class
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
How to call a method with parameters as objects from another class java?
The problem was that I was trying to add an object of the same class Member
to call the method from the other class Website
, which had a Member purchase
as a parameter.
So in order to correctly call that method, I used this code:
public void payForHoliday(Holiday test)
{
website.checkout(this, test);
}
For pointing to the method
checkout()
in theWebsite
class, I used anaddress
(Website website) declared as aninstance variable
inMember
class.The
this
keyword tells the program that the parameter is the object itself, which is calling The method.The
test
variable is placed as a parameter due to the fact that is a pointer from another class. (I changed the variable name to another name to avoid conflicts with the one in thecheckout()
method)
How to call a function from another class in python
There was a few things.
- When you define class methods, they must have
self
as the first parameter. - The part where you had an error is where you tried to call B as a variable. B is a class, and you must call it like any other class. This also applies when you are calling
A()
in class B.
Revised code:
class A:
def add_f(self, a, b):
return a + b
class B:
def sum_f(self, a, b, c):
return A().add_f(a, b) + c
print B().sum_f(1, 2, 3)
Update:
Thanks for taking my advice but you're still missing something. In class B you call a method from class A, but you need parentheses for that too! In class B, call class A as such:
A().add_f(a, b)
Related Topics
List of All Available Matplotlib Backends
How to Return a String from a Regex Match in Python
Django 1.7 - "No Migrations to Apply" When Run Migrate After Makemigrations
Python Parse Comma-Separated Number into Int
Tuple or List When Using 'In' in an 'If' Clause
Pandas Equivalent of Oracle Lead/Lag Function
Python/Selenium Incognito/Private Mode
Cleanest Way to Hide Every Nth Tick Label in Matplotlib Colorbar
Add Zeros to a Float After the Decimal Point in Python
How to Return a Subset of a List That Matches a Condition
Axes Class - Set Explicitly Size (Width/Height) of Axes in Given Units
Gunicorn Autoreload on Source Change
How to Unimport a Python Module Which Is Already Imported
Opencv Python: Cv2.Findcontours - Valueerror: Too Many Values to Unpack
Segmenting License Plate Characters
How Does Python Find a Module File If the Import Statement Only Contains the Filename