Closed jbytecode closed 4 months ago
The commit above implements some getter and setter functions to Individual class. Note that the member fields are still accessed in the whole program, so I didn't underscore them yet.
I likened it to encapsulation for private members in C#, as you mentioned.
yes, Python classes encapsulate their object field members, static objects, and methods by default. However unexpected mutations are main causes of some problems so we hereby restrict the access of private members.
For example, suppose that we mutate the content of an Individual like that
parent.chromosome = [1,1,1,1,1]
this use of accessing of the field may be a cause of a problem, just because the fitness value should be updated whenever the content is changed so
def setchromosome(self, value):
self.chromosome = value
self.fitness = self.problem.f(value)
guarantees that the change of content triggers the change of fitness at the same time.
Note: This use of setter is just an example so it does not mean that we really should change the definition of Individual. Please use this functionality when necessary.
Suppose the class is defined as below:
The instantiate the class A
and then suppose you get member as
This use of member fields is somehow problematic in some cases so we can avoid using members directly. It is better to call setter and getter functions (like in C# and Java):
Since we have no private members in Python objects, it is convenient to define with an underscore, e.g. _member. So the final use becomes
Note that list objects are passed with their references, rather than values. To prevent mutations, list objects can be recreated with the old values if it is necessary.