Question: In Python, we cannot explicitly set an class attribute to private or public. We can access class attributes directly using the dot notation. For

In Python, we cannot explicitly set an class attribute to private or

In Python, we cannot explicitly set an class attribute to private or public. We can access class attributes directly using the dot notation. For example: my_dog = Dog() my_dog._name = "Fido" print (my_dog._name) To discourage this, we use the underscore naming convention along with setters to change the attribute and getters to get the attribute. For example: my_dog Dog() my_dog.change_name("Fido") print (my_dog.get_name()) Why do we bother doing this? Why not simple directly access the attributes as shown in the first example?

Step by Step Solution

3.45 Rating (174 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Using getters and setters to access and modify class attributes is a way to encapsulate the data sto... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!