Class and instance attributes in Python

Let’s say Hi!

Oriented object programming OOP: is a programming paradigm based on the concept of “object” when data be gathered to form a package of features, a callable piece of code well structured and organized.

Class

A class is a blueprint for creating an object, a template describing a data based on the seamless between this objects. in computer science the use of template is crucial to facilitate the ergonomic of the data and the scalability of the program. So let’s walk through a very common procedure. an authentication of user which we could find it in every application.

User class is a template which every new user signup should follow, to create the user class we take use the “class” keyword followed by the class name and then the body of class indented as python flavor:

When a new user try to signup to the holberton application is following the User class. he is try to make his own copy of the class as known as an instance of class.

Attributes

So each registered user in the application should had a username and a password which represent the credential of the user and as we know this credentials are unique for each user, for each instance of our User class:

Here we come up to the instance attributes is a non sharable fields between the users.

By invoking the method ‘__init__’ we try to initialize the instance by his fields and add the two attributes to the namespace of the class User. a namespace is a set of dictionary keeping all the fields and attributes of the objects let’s checkout:

We found the method “__init__” as a key in the dictionary with the same attributes assigned in the class as value.

So we can distinguish two types of attributes “class attributes” which are a sharable attributes between all the instance of the class, and “instance attributes” a unique attribute belong to each instance of class.

In order to track the User attribute we use the builtin command dir:

When we look for the two fields “loged_in” and “username” is quite in the “dir” list as public instance but the password fields is prefixed by the User class coming to the way that python “encapsulate” variables in fact this is a name mangling in order to protect the variable from getting overridden.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store