I am trying to understand Static methods in java. I have done a basic python before, so I am trying to visualise the Java's static method in Python.
Is the static method in the code below
class test{
public static void main(String[] args) {
printHello();
}
public static void printHello(){
System.out.println("This is a Java's static method");
}
}
equivalent to this?
def printhello():
print("It is a printhello function")
class hello():
def printhello(self):
print("It is a printhello method of a instance")
As static methods can be accessed without creation of objects, def printhello would work like this.
And when a object is accessing static method in Java, the instance method provided in the python class would work like that.
If not, what would be right visualisation of a java's static method in python.
Thanks.
Here
class Hello:
def printhello(self):
...
you're passing a self reference to the method. This means it is an instance method.
A static method never owns a reference to an instance of its containing class by default.
Python class static methods are defined, usually, using the @staticmethod annotation, and they don't accept self
class Hello:
@staticmethod
def printhello():
...
So the above would become, in Java
class Hello {
public static void printhello() {
...
}
}
Java doesn't have the concept of first-level functions, so this
def printhello():
print("It is a printhello function")
isn't really translatable, but it's usually a more idiomatic way of defining free/static functions in Python.
As you may have understood, answering your question
Is the static method in the code below
...
equivalent to this?
No, it's not equivalent at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With