Learning Python: From Zero to Hero

Only the object can interact with its internal data.First, we need to understand how public and non-public instance variables and methods work.Public Instance VariablesFor a Python class, we can initialize a public instance variable within our constructor method..Let’s see this:Within the constructor method:Here we apply the first_name value as an argument to the public instance variable.Within the class:Here, we do not need to apply the first_name as an argument, and all instance objects will have a class attribute initialized with TK.Cool..We have now learned that we can use public instance variables and class attributes..Another interesting thing about the public part is that we can manage the variable value..What do I mean by that?.Our object can manage its variable value: Get and Set variable values.Keeping the Person class in mind, we want to set another value to its first_name variable:There we go..We just set another value (kaio) to the first_name instance variable and it updated the value..Simple as that..Since it’s a public variable, we can do that.Non-public Instance VariableWe don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work). — PEP 8As the public instance variable , we can define the non-public instance variable both within the constructor method or within the class..The syntax difference is: for non-public instance variables , use an underscore (_) before the variable name.“‘Private’ instance variables that cannot be accessed except from inside an object don’t exist in Python..However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member)” — Python Software FoundationHere’s an example:Did you see the email variable?.This is how we define a non-public variable :We can access and update it.. More details

Leave a Reply