I tried to enumerate the differences between java and python

** * Caution Add what you noticed in sequence **

A java shop starts using python and lists the things that surprised me with the difference. Also, leave the coping method.

switch statement

There is no switch syntax in python. It seems that the idea is that if there is no switch, it should be done with if. Alternatively, there is also a method using a dictionary.

Why is there no switch or case statement in Python? (Official site)

Method used in the dictionary


def function_1():
    print('function_1')
def function_2():
    print('function_2')

functions = {'a': function_1, 'b': function_2}

func = functions['b']
func()

↓ Execution result ↓
function_1

constant

There are no strict constants in python By naming it in all capital letters, it is treated like a constant. It's just a variable, so of course you can change it if you like.

Interface

There is no interface in python. There is a concept of abstract classes called ABC (Abstract Base Classes), so I wonder if there is any particular problem. All you have to do is make it an abstract method.

How to write an abstract class(abctest.py)


from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Cow(Animal):
    def sound(self):
        print("moo")

class Penguin(Animal):
    pass  #Does not implement abstract methods

if __name__ == "__main__":
    hanako = Cow()
    hanako.sound()

    taro = Penguin()  #I get an error when instantiating because I haven't implemented an abstract method

Execution result


moo
Traceback (most recent call last):
  File "abctest.py", line 19, in <module>
    taro = Penguin()
TypeError: Can't instantiate abstract class Penguin with abstract methods sound

Overload

There is no concept of overloading in python. Use the default argument settings and variadic arguments to do things like overloading.

An example of an error when trying to overload

This is no good


class Farm:
    def add(self, animal):
        print(animal)
    def add(self, animal1, animal2):
        print(animal1)
        print(animal2)

if __name__ == "__main__":
    farm = Farm()
    farm.add('Dog')
    farm.add('Jersey','Holstein')

↓ Execution result ↓
Traceback (most recent call last):
  File "farmtest.py", line 13, in <module>
    farm.add()
TypeError: add() missing 2 required positional arguments: 'animal1' and 'animal2'

This is OK

class Farm:
    def add(self, animal='Chicken'):
        print(animal)

if __name__ == "__main__":
    farm = Farm()
    farm.add()
    farm.add('Dog')

↓ Execution result ↓
Chicken
Dog
class Farm:
    def add(self, *args):
        if len(args) == 0:
            print('blank')
        for i in args:
            print(i)

if __name__ == "__main__":
    farm = Farm()
    farm.add()
    farm.add('Dog')
    farm.add('Jersey','Holstein')

↓ Execution result ↓
blank
Dog
Jersey
Holstein

ApplicationContext

There is no Java Servlet or spring framework in django that corresponds to an ApplicationContext that is broader than the Session scope. Are you using django?

Labeled break

There is no labeled break in python to use when getting out of a double loop in java. I don't use it much in java, so it's okay.

Scope of local variables

python is valid in the function. java is valid in the block.

This is awkward for a java shop ...

Field definition position

Note that if you write it like a java instance variable, it will mean a class variable in python! If I made a mistake at first, I was surprised that the movement was unexpected.

class Cow:
    type = 'Holstein'  #Class variables
    def __init__(self, name):
        self.name = name  #Instance variables
    def walk(self):
        print(self.name + 'Walk')

hanako = Cow('Hanako')
hanako.walk()

↓ Execution result ↓
Hanako walks

Recommended Posts

I tried to enumerate the differences between java and python
I tried programming the chi-square test in Python and Java.
Differences in syntax between Python and Java
Summary of the differences between PHP and Python
I tried to verify and analyze the acceleration of Python by Cython
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
I compared Java and Python!
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
I examined the data mapping between ArangoDB and Java
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to solve the problem with Python Vol.1
I tried to summarize the string operations of Python
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
Difference between java and python (memo)
I tried to touch Python (installation)
I tried to automate the article update of Livedoor blog with Python and selenium.
Differences between Python, stftime and strptime
I tried to illustrate the time and time in C language
I tried to display the time and today's weather w
[Python] I tried to visualize the follow relationship of Twitter
I tried to implement the mail sending function in Python
I want to know the features of Python and pip
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I tried to divide the file into folders with Python
I tried to compare the processing speed with dplyr of R and pandas of Python
I tried to move the ball
I tried to estimate the interval.
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I want to absorb the difference between the for statement on the Python + numpy matrix and the Julia for statement
I tried to solve the ant book beginner's edition with python
[Introduction to Python] I compared the naming conventions of C # and Python.
I tried to display the video playback time (OpenCV: Python version)
I tried to make a periodical process with Selenium and Python
I tried to easily detect facial landmarks with python and dlib
I tried to improve the efficiency of daily work with Python
How to display bytes in the same way in Java and Python
I tried to summarize Python exception handling
I tried to implement PLSA in Python
Differences in authenticity between Python and JavaScript
Differences between Ruby and Python in scope
I tried to recognize the wake word
I tried to implement PLSA in Python 2
Python3 standard input I tried to summarize
I tried to summarize the graphical modeling.
I tried to implement ADALINE in Python
I tried to estimate the pi stochastically
I tried to implement PPO in Python
Python: I tried the traveling salesman problem
How to use Python zip and enumerate
[Python] I tried to calculate TF-IDF steadily
Differences in multithreading between Python and Jython
I tried to touch Python (basic syntax)
Differences between Ruby and Python (basic syntax)
I tried the Python Tornado Testing Framework
[Python] I tried to reproduce the battle between the lion and the gazelle with a super cool mathematical formula called the Lotka-Volterra equation.
I don't really understand the difference between modules, packages and libraries, so I tried to organize them.
[Python] I tried to visualize the night on the Galactic Railroad with WordCloud!
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.