Term contract

  1. We call the author of an API “author.”
  2. We call the users of the API “clients.”

Getters and setters were invented in the first place

For data hiding purposes. That is, “no class attribute can function to the outside world, but provides an interface for the outside world to access.” This is a valuable lesson learned before us and should not be questioned (if you doubt it, you will one day come to the same conclusion).

In general, you need to use more

In fact, there is no code saving on the author side, as in Java, the biggest benefit is to simplify the client side of the call logic.

Such as

class Person:
    def __init__(self, name, age, gender):
        self._name = name
        self._age = age
        self._gender = gender

    def name(self):
        return self._name

    def name(self, value):
        self._name = value

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = value

        return self

Copy the code

The client call is changed from p.get__name () to p.name. this seems more logical to the client.

Personally, I prefer Java’s set of getters and setters

I lean towards this because:

  1. It seems that not all class attributes are needed by the outside world
  2. I usually write getters/setters on demand, and then fill in the corresponding getters/setters when I need them
  3. Sometimes AS a client, I actually prefer itp.get_name()The way this is called,Better consistency

There is only one caveat

Don’t put too much logic in your getters and setters.

By stuffing too much logic, you break the contract between the author and the client for getters/setters.