Nov-09-2020, 04:16 PM
"anti-pattern" translates to "You are doing it wrong".
Everything in Python is open to the public. There is no concept of "private" like there is in C++ and most other OOP languages. Because all things are public and because Python programmers are lazy, the common practice (pattern) is to directly reference instance variables using namespace.variable_name. This is generally a good thing because it results in less code to write and maintain and reduces the amount of code someone has to learn to use you class. It would be very common for somebody using your class to directly reference eyes as spider.Body.top.eyes=8 instead of using the spider.set_eyes(8) method. This is so common that most class authors only write a "setter" if setting a class attribute has some side effect.
For example, let's say you have a set_feet() method that also sets the number of legs.
Everything in Python is open to the public. There is no concept of "private" like there is in C++ and most other OOP languages. Because all things are public and because Python programmers are lazy, the common practice (pattern) is to directly reference instance variables using namespace.variable_name. This is generally a good thing because it results in less code to write and maintain and reduces the amount of code someone has to learn to use you class. It would be very common for somebody using your class to directly reference eyes as spider.Body.top.eyes=8 instead of using the spider.set_eyes(8) method. This is so common that most class authors only write a "setter" if setting a class attribute has some side effect.
For example, let's say you have a set_feet() method that also sets the number of legs.
def set_feet(self, num_feet, num_legs=None): self.feet = num_feet self.legs = num_feet if num_legs is None else num_legsThis makes it easier for the class user without adding much code and it enforces consistency between legs and feet. Another reason for writing setters is they provide a handle for connecting your classes to GUI controls and timers and things that need a function.