Python for C# Developers (function)

I think I wrote C# code the most in my career. C# is almost like a mother tongue to me just like Japanese language is though I’ve been speaking “foreign languages” like Groovy and Python quite a bit. When I have to think deep about something, I always go back to my mother tongue. I think I’m going to try it out with C#. In this series, I’m going to write some sample code in C# and then translate it into Python.

I won’t start like what variables are, strings are, integers are… those very basic concepts like in any other “tutorial” sites. I will go straight into what may be useful.

I’m going to talk about functions this time. Functions can be void or ones that return something. Let’s see them in C#.

using System.IO;

public class Functions
    {
        public void WriteString(string path, string text)
        {
            File.WriteAllText(path, text);
        }

        public int Add(int a, int b)
        {
            return a + b;
        }
    }

Now let’s see them in Python.

class Functions:
    def WriteString(self, path, text):
        with open(path, 'w') as f:
            f.write(text)

    def Add(self, a, b):
        return a + b

This is not really “Pythonic”. Let’s change the Python code into more Pythonic way.

class functions:
    def write_string(self, path, text):
        with open(path, 'w') as f:
            f.write(text)

    def add(self, a, b):
        return a + b

Python coding standard is, in short, lower case everything connecting words with underscore. The details can be found here.

It’s very easy to see what the differences are but I will try to explain in words.

return keyword returns a value to the caller of the function.

To create a class, Python uses the same “class” keyword. Whenever you use a keyword (such as if, while, for and etc…), it has to end with : (semi colon). When you define a function, it has to start with def. There is no distinction between function that returns value or not.

“with” keyword in Python is equivalent to using in C#. It makes sure that any resource (such as file, database or network connection) opened this way will be closed when the code gets out of the context. (context manager)

 

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *