Python Forum
Preserve Encapsulation while Displaying Information
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Preserve Encapsulation while Displaying Information
#2
This is not Java.  As far as python goes, we don't code this way.  Unless a getter/setter actually does work, you don't write one.

So your car should just be:
class Car:
    def __init__(self, ID, name, tire, engine):
        self.ID = ID
        self.name = name
        self.tire = tire
        self.engine = engine
 
    def __str__(self):
        template = "ID: {ID} Name: {name} Tire: {tire} Engine: {engine}"
        return template.format(**vars(self))
If someone wants to access an attribute of tire they just do so using mycar.tire.name for example.
Python has a "we are all consenting adults" philosophy on data  access.  There are no private/public attributes so not only is writing getters/setters not recommended; it is actually pointless.  I can access all those attributes if I want to.

Basically, Python doesn't enforce encapsulation (and if you are trying to enforce it you are writing bad python).  You still use encapsulation by coding responsibly.
Reply


Messages In This Thread
RE: Preserve Encapsulation while Displaying Information - by Mekire - Dec-07-2017, 03:03 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Encapsulation codinglearner 2 1,568 Apr-02-2024, 01:26 PM
Last Post: DataScience
  python-docx: preserve formatting when printing lines Tmagpy 4 2,345 Jul-09-2022, 01:15 AM
Last Post: Tmagpy
  tabula-py, how to preserve a read_pdf() format and export to csv abcoelho 2 3,494 Mar-24-2021, 08:34 PM
Last Post: abcoelho
  Function encapsulation Oldman45 4 2,398 Jan-22-2021, 11:38 AM
Last Post: Oldman45
  How to preserve x-axis labels despite deleted subplot? Mark17 1 2,060 Dec-23-2020, 09:02 PM
Last Post: Mark17
  Preserve xml file format tanffn 3 4,097 Jan-03-2020, 09:35 AM
Last Post: Larz60+
  Pygal: Displaying information for each data point KirkmanJ 0 1,917 Jul-29-2019, 01:10 PM
Last Post: KirkmanJ
  Encapsulation issue iFunKtion 4 4,075 Mar-07-2017, 10:13 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020