What is the best practice to declare and initialize in __init__ function?

Continuing the discussion from Python should introduce the concept of variable declaration to prevent potential issues that may arise from variable redefinition. :

Hi all, I’m new here and I have a little question when I take up writing my own classes. The biggest problem is about class initialization. Python mixes declaration with assignment, so I’m not sure whether I should do this:

class myclass:
    def __init__(self, object_):
        # declaration
        self.__var = None
        # assignment
        self.__update_var(object_)
    def __update_var(self, item):
        # some code
        self.__var = something

Or,

class myclass:
    def __init__(self, object_):
        # declaration and assignment
        self.__var = self.__get(object_)
    def __get(self, item):
        # some code
        return item

Neither of these seem proper. In the first case, this seems redundant to refer to var twice. And all of the update functions have side effects, which means they cannot be easily reused out of the class. In the second case, if I need to update __var in another function, I need to manually do self.__var = self.__get(var) again. This seems tiresome when I have coupled variables:

 class myclass:
    def __init__(self, object_):
        # declaration and assignment
        self.__varA = __get(object_)
        self.__varB = __get(self.__varA)
        self.__varC = __get(self.__varB)
    def __get(self, item):
        # some code
        return item
    def calc_then_reset(self, another_obj, options):
        # If I change self.__varA here, 
        # I need to manually update all of the consequential variables.

Neither can I change the order of clauses when declaring. (Sometimes I want __varA and __varC to be public while __varB private, and it is impossible to put all private variables in one region and public ones in another.) Nor could I make it clear like this:

 class myclass:
    def __init__(self, object_):
        # declaration and assignment
        self.__varA = None
        self.__varB = None
        self.__varC = None
        self.__updateA(init_value)
        
    def calc_then_reset(self, another_obj, options):
        results = xxx
        self.__updateA(results)

    def __updateA(self, results)
        self.__varA = xxx
        __updateB(self.__varA)
    def __updateB(self, varA)
        self.__varB = xxx
        __updateC(self.__varB)
    def __updateC(self, varB)
        self.__varC = xxx

So could I ask for the best practice to do this? Thank you all!

This looks like a problem which may be served by use of descriptors. Possibly just by using @property. Have you looked into either of those?

It looks like you’re trying to force attribute protection onto Python. Perhaps you’re coming from a language where this is common, and it makes you feel comfortable?

I would encourage you to try the ‘pythonic’ paradigm: no protection at all

class MyClass:
  def __init__(self, var):
    self.var = var

I understand depending on your background something in you may initially protest against this. But consider how this class is going to be used. Only by yourself? Then agree with yourself some conduct that will ensure that MyClass.var will only be changed appropriately. Only within this repository, but by a team you need to work together with? Then agree on such a conduct with your team. Most teams already have such a conduct. (Even if it usually isn’t explicit.)
Is this a library, and you feel the need to protect yourself for the sake of inheritance by other people you have no relation with? Design the interface with the user so that they don’t need inheritance. And use a @final decorator if it makes you feel better.

As I said, I understand this can feel weird. But sincerely, give it a try before you dismiss it.

I’m sort of unclear on what your ultimate goal is with the code snippets given, but as one suggestion, if you want to be explicit about what attributes are allowed to be defined/assigned on your class and want to enforce that, you can use the __slots__ attribute like so:

class A:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

Which will raise an error at runtime if you try to define any attribute on an instance of A that isn’t in A.__slots__:

In [1]: class A:
   ...:     __slots__ = ('x', 'y')
   ...:     def __init__(self, x, y):
   ...:         self.x = x
   ...:         self.y = y
   ...:

In [2]: a = A(1, 2)

In [3]: a.x = 1

In [4]: a.y = 2

In [5]: a.z = 3
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[5], line 1
----> 1 a.z = 3

AttributeError: 'A' object has no attribute 'z'

Hmmm… Actually, I’m trying to adapt scientific computing into OOP styled python (specifically, PySCF). I knew from DRY principle in The Pragmatic Programmer (page 8 in this pdf) that we could write code like this:

class Line {
    private double length; 
    private Point start; 
    private Point end;

    public Line(Point start, Point end) {
        this.start = start; this.end = end;
        calculateLength() 
    }
    public void setStart(Point p) {
         this.start = p;
         calculate_length() 
    } 
    public void setEnd(Point p) {
        this.end = p;
        calculate_length() 
    }

Point getStart(void) { return start; } 
Point getEnd(void) { return end; }
double getLength() { return length; }

Because of this setter function, every time start and end changes, lengthwill change automatically. (I like this style.)

However, for programs with calculation as the main process, this situation is much more complicated. The most expensive part is the key step of some calculations (i.e. calc process in setEnd becomes much more expensive while setStart is relatively cheap, so we can’t automatically update length in setEnd every time a property of Point end changes. Instead, manually after all parameters have been set properly, run.) . Moreover, during the process of the expensive one, there may be some intermediate variables shared by many subroutines.

What I want to do is taking the advantage of OOP. Only the starting data and the final results matter. So I want to set the starting readable and writable, the ending readable (for further advanced calculations), while keeping those unimportant intermediate variables private.


I’m a green hand in software engineering and I don’t really know how many variables I should set public. The more I set, the more inner functions are coupled. While the less I set, the more arguments a function will have. When I write subroutines, I need to do a lot of this:

# In a class
def calc(self, A=None, B=None, C=None):
    if A is None:
        A = self.A
    if B is None:
        B = self.B
    if C is None:
        C = self.C
    D = self.D # intermediate shared by many subroutines.
    # Troublesome? I think so.
    # some code to calc using A, B, C and D
    return xxx

I write like this so that I can write a function in this class like this:

def wanna_self_consistent_convergence(self):
    while True:
        old_status_A = self.A
        old_potential = self.potential
        new_status_A = get_from(old_potential)

        new_potential = calc(new_status_A)
        if abs(new_potential - old_potential) < threshold:
             break
        self.A = new_status_A
        self.potential = new_potential

While in other cases, when others want to do a single calculation using the current properties, he could do this:

mycalc = myclass(init_vars)
mycalc.calc() # using current vars with no need to update

I want to know best practices to avoid these.


Another question I have is that I don’t really know how to declare a variable in python. I tend to do this:

class myclass:
    def __init__(self, obj_):
        # declaration
        self.varA = None
        ...
        # initialization
        self.varA = self.updateA(obj_)

But it seems not pythonic. And another question is: should I write self.varA = self.updateA(obj_) or self.updateA(obj_) in __init__ function?

Thank you!

Yes, maybe __slots__ is what I want. Thank you.
And, I’m not sure whether I’m writing in a pythonic way. It is said that assigning is also initializing. I’m new to contributing to software so I want to be recognized by the others.

In case you missed my first post: have you looked into descriptors and @property? I think these tools may be of use to you here.

Yes I am already trying @property. I’d to say what I meet may be complicated…
Thank you!

Is it a requirement that your classes are mutable? I think there’s something to be said for not changing the start or end on existing Line objects, and instead creating a new Line. Then your Line class simply becomes this:

class Line:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.length = calculate_length(start, end)

    def replace_start(self, new_start):
        return Line(new_start, self.length)

    def replace_end(self, new_end):
        return Line(self.start, new_end)

Each Line instance has a length that’s calculated once at initialization. Use replace_start() or replace_end() to create a new instance with another start or end, and with a new automatically calculated length. You don’t have to worry about updating the length when updating start or end of an existing instance, because that doesn’t happen anymore.

You could use a dataclass to help make the instances immutable:

import dataclasses
import math

@dataclasses.dataclass
class Point:
    x: float
    y: float

def calculate_length(a: Point, b: Point) -> float:
    return math.hypot(a.x - b.x, a.y - b.y)

@dataclasses.dataclass(frozen=True)
class Line:
    start: Point
    end: Point
    length: float = dataclasses.field(init=False)

    def __post_init__(self): 
        # Unfortunately this gets a bit ugly to be able to set length even
        # with frozen=True
        object.__setattr__(self, "length", calculate_length(self.start, self.end))

    def replace_start(self, new_start: Point) -> Line:
        return Line(new_start, self.end)

    def replace_end(self, new_end: Point) -> Line:
        return Line(self.start, new_end)

def main():
    a = Line(Point(0, 0), Point(3, 4))
    print(a)
    b = a.replace_start(Point(1, 1))
    print(b)

if __name__ == "__main__":
    main()

That would print:

Line(start=Point(x=0, y=0), end=Point(x=3, y=4), length=5.0)
Line(start=Point(x=1, y=1), end=Point(x=3, y=4), length=3.605551275463989)

Thank you for your elaborated answer. Maybe because I’m not a native English speaker and my description is not accurate. I apologize for that.

I know the advantages of OOP. It packs all of the related data and methods into a class so that when another one invokes setter function, all of the fast, unimportant, and trivial process are handled implicitly and automatically. Such properties enable better encapsulation, and many client-oriented projects need this.

My class is indeed mutable, and your answer does enlighten me. I could turn a OOP language into a structured program in this way. But as you might have understood, the biggest difficulties are from merging these styles together. And what’s even worse is that different people adopts different logic when contributing to the same open-source project.

I think I’d better describe the backgrounds of what I’m doing. Users will enter a structure of a molecule. It contains all of the XYZ coordinates of nuclei of a molecule. e.g. For a water molecule, it looks like

mol = Mole()
mol.atom = '''
    O 0 0 0;
    H 0  0.748 0.584;
    H 0 -0.748 0.584
    '''
mol.temperature = 298.15 # Just as an example
mol.pressure = 1

And instant information, such as num_of_electrons, num_of_cores could be easily calculated when we change any of these attributes. This looks like the Line instance above.

A user wants to know detailed information. e.g. electron_density_around_atoms matrix attribute. And this is assigned from the most time consuming part of a scientific program. We do that by labor-intensive calculations. They include integrals of spacial functions of an electron when we want to calculate how much every two electrons interacts. And it also includes iteration, because the current algorithm follows such a self-consistent procedure.

1. Guess the approximate potential around the molecule

2. For electrons 1 to 10, calculate their own orbitals accordingly
3. Calculate the potential generated by these rough orbitals
4. Check if this potential varies from the last potential. 
    If so, terminate, otherwise, loop back to step 2.

In conclusion, the number of total complexity is about O(N^4). Very expensive.

Maybe I have written too much. But I appreciate it if you understand me. I’d say, we cannot re calc immediately after num_of_electrons change, instead, after all variables are set, do.

So, this sounds like neither structural programming nor object-oriented programming. It is the combination of both. Neither of the styles are perfect for me. It isn’t following the simple OOP style.

The step 2 and step 3 could be divided into many subroutines. And these takes up most of proportion of methods in this class. They sometimes share some common intermediate variables, but these intermediate variables are continuously updating and NOT important for the final result. So it is troublesome whether to parse them as arguments (not important variable and make the subroutine argument list complex) or to save it as instance attribute (big, continuously updating, and not important for final results). It also matters whether I employ assigning self. attributes from getters after returning from subroutines strategy or the updating self. attributes from subroutines one.

Do you feel exhausted now? I do, so that’s why I’m asking here. And that’s the reason why many people are still using Fortran. Some of them don’t want to try OOP at all. What they write may be not reusable either.

Is there a reason that you need to calculate it at all until the user needs it? Rather than calculating proactively, you could do something like this:

class Mole:
    def __init__(self):
        self._atom = ""
        self._num_electrons = None

    @property
    def atom(self):
        return self._atom

    @atom.setter
    def atom(self, value):
        self._atom = value
        self._num_electrons = None

    @property
    def num_electrons(self):
        if self._num_electrons is None:
            # recalculate here
            self._num_electrons = 1
        return self._num_electrons

Do you mean, to invoke all of the calculating functions manually? It is a good strategy. And originally I thought a class should be written like this. Just a lot of getter function will help me do that. Until I read The Pragmatic Programmer, which told me a concise way like this:

 class myclass:
    def __init__(self, object_):
        # declaration and assignment
        self.__varA = None
        self.__varB = None
        self.__varC = None # B and C are consequential vars from A. e.g. C = A + B
        self.__updateA(init_value)
        
    def calc_then_reset(self, another_obj, options):
        results = xxx
        self.__updateA(results)

    def __updateA(self, results)
        self.__varA = xxx
        __updateB(self.__varA)

    def __updateB(self, varA)
        self.__varB = xxx
        __updateC(self.__varB)

    def __updateC(self, varB)
        self.__varC = xxx

Maybe I shouldn’t have read the book, but it did inspire me why to embrace OOP. It omitted the duplicated updating process in calc_then_reset (and there may be many calc_then_reset functions, where only __updateAs are needed). Maybe I shouldn’t have known that… :smiling_face_with_tear:

I don’t know whether this sounds pythonic. And I’m really grateful if you can share your opinions.
Thank you!

Sorry, I don’t really understand you here. Maybe let’s take a different tactic - why don’t you describe the public interface that you think would be most comfortable for the user? Then it can be easier to work backwards and find an appropriate internal structure to achieve that.

I would like the user to have the least manual settings.
That’s to say, immediately after he inputs the atoms, all of the other attributes are updated automatically. So I think setters and updaters should exist, just like when we insert a stack frame to a stack, the total number of elements increments with no need of manual intervention.

However, just as you found above, some of the procedures are too expensive. And these needs to be reserved for the user to do manually. After he feels he sets all good parameters, he will run the expensive part.

This could be a mix between structural programming and object-oriented programming. And definitely, if we want the user to intervene and operate less, the program gets complicated.

Some of the variables should follow the automatically updated routine, and if all attributes are of this type, we could simply structure the program using setters and getters. A user can freely update any attributes, and get any other ones at any time precisely.

But some other ones follow the structured programming. i.e. This kind of programs are sequential, Running from head to end without backward checking. The user may get a correct result when he only invokes the num_electrons once. He will have a wrong result if he inits the class, asks for the num_electrons, changes the atom attribute, and asks again.

It is complicated, but I think it is inevitable. Thank you for your effort to discuss with me.

It still feels like @duncathan’s example fits very well here. I don’t see where you’re seeing “to invoke all of the calculating functions manually”. I would extend that code with an ability to force expensive calculation now; and maybe a generic “dirty” flag instead of per-field state; I did something roughly similar in some projects in the past:

class Mole:
    def __init__(self, atom):
        self._atom = atom
        self._mark_dirty()

    def _mark_dirty(self):
        self._dirty = True
        self._num_electrons = None
        self._num_neutrons = None
        self._num_protons = None

    # called whenever you access a field that needs recalculation,
    # but you can also call it manually if you want to force the long calculation to happen _now_
    def recalculate(self):
        if not self._dirty:
            return
        a, b, c = some_expensive_calculation_here(self._atom)
        self._num_electrons = a
        self._num_neutrons = b
        self._num_protons = c
        self._dirty = False

    @property
    def atom(self):
        return self._atom

    @atom.setter
    def atom(self, value):
        self._atom = value
        # optional enchancement: only _mark_dirty() if ._atom actually changed
        self._mark_dirty()

    @property
    def num_electrons(self): # identical for num_neutrons, num_protons
        self.recalculate()
        return self._num_electrons

That’s great! An additional variable could resolve the problem! Thank you!