How do I call outside function from class in python
To call the class method, you can create an instance of the class and then call an attribute of that instance (the test_def
method).
def test(t):
return t
class ClassTest(object):
def test_def(self):
msg = test('Hi')
print(msg)
# Creates new instance.
my_new_instance = ClassTest()
# Calls its attribute.
my_new_instance.test_def()
Alternatively you can call it this way:
ClassTest().test_def()
Sidenote: I made a few changes to your code. self
should be used as first argument of class methods when you define them. object
should be used in a similar manner.
Calling a function from outside class with user input without using global
So, I think you neither did read documentation nor watched/read any tutorial about Python classes. So I will explain it here for you.
Class is a "object project". It may have predefined methods, predefined values. It also may have a way to construct these dynamically.
Class object at first need to be instantiated and then initiated. That means that firstly you need to create an instance of a class, then to initiate default values.
Python has 2 methods for this.
__new__()
creates a new instance of a class and returns it. It's already realised for every Python class, but there may be special cases for you to override it.
__init__(*args, **kwargs)
initiates values of a class. You must define non-static values here or globally in class.
So, creating a class object is achieved in python by calling class like this
A_instance = A(*args, **kwargs)
That in words means create me instance of A with these args and kwargs
So in your code, you are using (actualy overriding) __init__(*args, **kwargs)
with args = (NUMBER_INPUT,)
and kwargs = None
.
Thus you must provide NUMBER_INPUT every time you create an object of phone, like so:
phone1 = phone("123-456-7890")
phone2 = phone("098-765-4321")
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.
PHP - Class calling functions outside the class
You can extend a class to another class to access parent class functions and properties in subclass. Functions declared private cannot be accessed like that. You can also pass object of another class to to one class as an argument to the constructor.
if you have a class name parent :
class parent{
// properties and methods
}
Then you can access its functions if you extend it to your class :
class child extends parent{
// code
}
OR
$parent = new parent();
$child = new child($parent);
Then in child class you can use :
function __construct($parent) {
$this->connection = $parent;
}
Then within other functions in child class you can access the parent class methods using
$parent->connection->function_name()
Having a class member function call a function outside the class
computeValue
needs the declaration of class A
, so declare A
before it:
class A
{
};
int computeValue(vector<A*>ex)
{
//implementation of algorithm
}
Is it even possible for member functions of classes to call non-member functions?
Of cource, yes.
Call function from outside a class
Your problem is not outside, but inside:
public function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * $this->factorial($number-1));
}
}
If you want to refer to another method you have to use $this->methodname
where $this
refers the instance:
The pseudo-variable
$this
is available when a method is called from within an object context.$this
is a reference to the calling object (usually the object to which the method belongs (...))
I suggest to read PHP - OOP - The Basics.
How to call "class method" from outside class in JavaScript?
If you are going to use that style of class, then you must first make an instance of it.
var a_view_model = new ViewModel();
a_view_model.escapePressed();
… but if you just want to have a static method, then you probably shouldn't be using a constructor function in the first place
var view_model = {
escapePressed: function () { };
}
and:
view_mode.escapePressed();
Related Topics
Using JavaScript to Detect Whether the Url Exists Before Display in Iframe
What Does This Format Means T00:00:00.000Z
How to Output a Pdf Buffer to Browser Using Nodejs
Show Virtual Keyboard on Mobile Phones in JavaScript
Save State When Refresh Page - Reactjs
Jquery, Line Break in Textarea.. Don't Get \N and Get ↵
How to Remove the Div That a Button Is Contained in When the Button Is Clicked
Development Server of Create-React-App Does Not Auto Refresh
Handling Multiple Http Responses One by One in Angular 6
Check If Page Gets Reloaded or Refreshed in JavaScript
How to Import File from Public Folder in React Application
Clear an Input Field With Reactjs
Changing the Value of Json Object's Key, Changes Other Values Also
Amount of All Goals of One Team (From Json)
How to Update a Variable After Button Click
Show/Hide Select Options Based on Value of Another Select Using Javascript/Jquery
How to Force Update Child Component from Parent Component in Reactjs