Home > OS >  Code inside of class outside of methods vs code outside class
Code inside of class outside of methods vs code outside class

Time:11-02

Here are two snippets of code:

Code 1:

# -*- coding: utf-8 -*-
class Foo:
    with open('myfile.json') as f:
        bar = json.loads(f)
    del f

    def __init__(self):
        print('Constructor')

# end of file

Code 2:

# -*- coding: utf-8 -*-
class Foo:
    def __init__(self):
        print('Constructor')

with open('myfile.json') as f:
    Foo.bar = json.loads(f)
del f

# end of file

Is there any difference between these two codes? If not, which one is to be preferred?

CodePudding user response:

Code 1: The outside-of-method code gets run once at the time of the definition of the class.

Code 2: The outside-of-method-and-class code gets run once during module import.

Since class definition happens at module import, the outcome should be exactly the same:

In either variation you end up with a class Foo whose class variable bar is set to the output of json.loads(f).

What's preferred? That's ultimately a matter of taste, isn't it? Code 1 emphasizes that this json and bar business belongs to the class. Code 2 emphasizes that our module does something special upon import. Sometimes that's an important point to make.

CodePudding user response:

Both snippets achieve more or less the same thing, with the difference in cleanliness. In the first snippet, when reading this piece of code, you already know that the bar contains the contents of a file. In the second snippet, however, you don't know that the class has a variable bar until you see the end of a file.

  • Related