Introduction

Rami Louhibi
11 min readJul 17, 2021

--

A Python object has two types of attributes: Class Attribute and Instance Attribute.

What’s a class attribute?

As the above example, class_attr is a class attribute and self.instance_attr is an instance attribute. Sometimes it’s really confusing. Why we have two types? Why not always define attributes as class attribute or instance attribute? What are differences of them? This post will uncover the mystery for you.

class MyClass(object): class_attr = 1 def __init__(self, value): self.instance_attr = value

What’s an instance attribute

Object Oriented Programming is not a programming language, but rather a model in which programs are organized around data or objects. OOP uses the concept of objects and classes. A class can be thought of as a ‘blueprint’ for objects. These can have their own attributes (characteristics), and methods (actions they perform). In Python everything is an object. Objects are a representation of real world objects like cars, dogs, house, etc. They all share data and behavior.

As an object oriented language, Python provides two scopes for attributes: class attributes and instance attributes. Think of a Class like a blueprint from which different objects are created with the same blueprint.

Each object, or in this case a car, is an instance of class car (image below). The cars can have data like number of wheels, doors, seating capacity, and behaviors: accelerate, stop, display how much fuel is left and more. Data in a class are called attributes and behaviors are called methods.

Data → Attributes & Behavior → Methods

Again, a class is like a blueprint for which other objects can be created. So with class instrument, objects like piano and guitar can be made. From guitar other objects can be made from it and they also can inherit attributes and methods from guitar and instrument if applied to them.

Another example of classes and objects in this picture

Instance Attribute

An instance attribute is a Python variable belonging to only one object. It is only accessible in the scope of the object and it is defined inside the constructor function of a class. For example, __init__(self,..).

Class Attribute

A class attribute is a Python Variable that belongs to a class rather than a particular object. This is shared between all other objects of the same class and is defined outside the constructor function __init__(self,…), of the class.

Differences Between Class and Instance Attributes

The difference is that class attributes is shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. The attribute of an instance on the other hand is unique to that instance.

__dict__

A __dict__ is a dictionary or maping objet used to store an object’s attributes. How does Python deal with the object and class attributes using the __dict__ ? Well, each instance is stored in a dictonary.

Creating Classes and Instance Pythonic and non-Pythonic

A non-Pythonic way would be like this:

class Square:
def __init__(self, size=0):
if not isinstance(size, int):
raise TypeError("size must be an integer")

if size < 0:
raise ValueError("size must be >= 0")

self.__size = size * size def area(self):
return self.__sizet__width()

The disadvantage comes when we need to modify the code. The pythonic way of doing it would be to use getter and setter property methods.

class Square:
def __init__(self, size=0):
self.size = size @property
def size(self):
return self.__size @size.setter
def size(self, value):
if not isinstance(value, int):
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value def area(self):
return self.__size * self.__size

The advantage of using property allows us to attach code to the self.size attribute and any code assigned the value of size will be called with size in def size.

Python is not my favorite introduction to object oriented programming, or OOP, but it’s definitely not the worst. Just remember, everything in Python is an object.

What are all the ways to create them and what is the Pythonic way of doing it

Introduction

As a coder (in my head), I always like to start things by describing data types. I think they are an excellent way to learn and explain any new concepts of language. So what are data types in python ?? Lets take a look —

A data type or simply type is an attribute of data which tells the interpreter how the programmer intends to use the data. As we all know, The most common data types in python are float (floating point), int (integer), str (string), bool (Boolean), list, and dict (dictionary). But unlike C or C++, Python will automatically determine which data type it will store data as. but you need to be aware of data types in order to convert data from one type to another(also called as Typecasting or Type conversion). Lets look at an example of basic data type (List) to understand the language and programming as a whole .

output //
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'dict'>
[<class 'int'>, <class 'float'>, <class 'str'>, <class 'bool'>, <class 'list'>, <class 'dict'>]

Remember — We can create our own data structures in python apart from the data structures provided by python. All you have to do is create a class and define your own methods in that class. That’s how a dataframe of pandas is created … But i will write about it some other day. For now lets stick to some basics !!

Basic List Methods

Lets look at some List Methods to insert and remove an element from the list …

  1. append — to add an element in a list.
    Performance — Time Complexity for appending an element at the back of the list is o(1) while anywhere else is o(n)
  2. remove — to remove an element in a list
    Performance — Time complexity for removing an element in the list is o(n) Time Complexity for Searching an element in List is always o(1)
output //
[1, 2.0, 'Hello World', True, [1, 2, 3, 4, 5], {'key': 'value'}, (1, 5.0)]
1
[2.0, 'Hello World', True, [1, 2, 3, 4, 5], {'key': 'value'}, (1, 5.0)]

Manupalating List Items

  1. lambda Function : they are written in 1 line and used to define custom functions
  2. map() Method (also called as a vector method in DataScience): use map function to map a custom function defined by you to every element of a list. map method takes 2 arguments —
    a. function you want to apply
    b. list you want the above function to apply
  3. enumerate() Method : The enumerate() method adds counter to an iterable and returns it. The returned object is a enumerate object.
output //
[1, 4, 9, 16, 25]
[1, 8, 27, 64, 125]
<enumerate object at 0x7f0cf44e4b40>
iterater is : 0 and value is Cat
iterater is : 1 and value is Dog
iterater is : 2 and value is Dog
iterater is : 3 and value is Tiger
iterater is : 4 and value is Lion
iterater is : 5 and value is Goat

Generators and Decorators :

  1. Python generators are a simple way of creating iterators / iterable objects . It is something which can be paused at the function call time and can be resumed anytime during the life cycle of the entire program by using next() function .
  2. Decorators are first class objects in python . It means that they can be passed by reference in any function . Decorator is just a fancy name and way of passing function as an argument to another function. they are also called as callable objects that takes in a function and returns or change the behaviour of that function .

*args and **kwargs

args and **kwargs are the most important keywords which i personally use a lot in my coding style and programming practice. well, imagine this !! you are creating a function and you don’t know the expected number of parameters . we use *args in that case and if its a dictionary , then use **kwargs .

What are the advantages and drawbacks of each of them

1. Quality Content

Medium has a big audience and it grows rapidly. Due to its focus on perfecting the writing and reading experience, it was just a matter of time until it attracts writers and readers from all over the world. The result was simple and pleasing — a community gathered around quality content. This was the main reason why we decided to blog here.

Pros:

  • Target audience. Medium allows you to reach the right audience with your content. Focused on tags and readers’ preferences, you will reach your target audience quickly since they can find you easily.
  • Content you’re looking for. If your content is good, people will interact with it. Medium is not like Social Media platforms where you can see everything from cat videos to pages like Squatting Slavs In Tracksuits, it’s quality content that suits your needs.

Cons:

  • Not a stand-alone. If you want to reach a wider audience, you have to promote your content on other platforms since the Medium community is still quite small.
  • No control over content. Medium can be shut down without a warning. If your content is based on this platform, it can be lost forever when/if Medium decides to change its terms and conditions. Or when/if it completely shuts down.

2. User Experience

At first sight, the UI is gorgeous. Everything’s clear and simple, and the main focus is text. For a content based platform like Medium, the design fits the needs very well and almost every part of it is user friendly.

Pros:

  • Good reading experience. A lot of white spaces, high quality typography, mobile optimization and overall simple, yet beautiful design are just some parts of user experience you get while reading a Story or scrolling through the feed.
  • User friendly CMS. When writing a Story, all the options, tools and draft previews are easy to use and clearly designed.

Cons:

  • No like/share distinction. When reading a Story, you can only respond (comment), highlight and share (recommend). There’s not a simple way of saying “I like this Story” without interacting with it in any way mentioned above. A simple Like or Love would do the job here.

3. Search Engine Optimization (SEO)

SEO is one of the main reasons we decided to publish on Medium. With its wide audience and strong SEO ranking, it’s easier to hop on the train than to build your own (for now).

Pros:

  • SEO ranking. In most cases, it’s tough to keep up with the SEO ranking. A great deal of keeping up with it goes to updating your content regularly. On Medium, your blog won’t suffer the ranking if you don’t post for a while.
  • An optimized platform. When writing, Medium automatically matches your writing with appropriate HTML elements. For example, when you want a quote, just mark it as a quote and Medium will treat it like that in code. Same goes for all other elements (like headlines).

Cons:

  • Helping Medium. If your blog is popular and frequently visited, you’re building SEO ranking for Medium. The traffic does not go to your website and Medium is the one that benefits from your writing and storytelling skills.

How does Python deal with the object and class attributes using the __dict__?

What is __dict__ method?

  1. According to python documentation object.__dict__ is A dictionary or other mapping object used to store an object’s (writable) attributes.
  2. Or speaking in simple words every object in python has an attribute which is denoted by __dict__.
  3. And this object contains all attributes defined for the object. __dict__ is also called mappingproxy object.

Consider dict and list objects in python lets use this method in these objects.

dict

list

Using __dict__ method for user-defined objects and classes.

As from the above code, we can observe that when __dict__ is called for the object of class DogClass we get the dictionary for the defined attributes and when the same function is called directly for the Class we get all the inbuild defined variables.

Now let’s talk about vars() function in python.

  1. The vars(object) function returns the __dict__ attribute of the object as we know the __dict__ attribute is a dictionary containing the object’s changeable attributes.
  2. If no value is specified for the vars() function it acts as pythons locals() method.

Calling vars() without argument. In this case, we are defining two global variables a and b.

a = "Hello"b = "World"vars()

vars

vars

As we know vars() gives us dictionary representation of all defined variables in the scope of a defined python script. let’s call this variable for inbuilt objects and user-defined objects. This is the same as calling __dict__ on the object.

Examples of vars() (This content is Optional)

You want to create a string in which embedded variable names are substituted with a string representation of the variable’s value.

In the above example, the first method uses a well-known method to substitute the variables but the second method uses vars() function to substitute the variables defined in the scope of the script(global scope).

Let’s look at the scope of the script by calling vars() here they are defined dog_name and eye_color are defined as key-value pair in the global scope and format uses these keys to substitute these values.

Now the main problem with string.format() is if there are missing values found we get an error. Hence over here we can leverage python’s own __missing__() dunder method. The below defined MissingClass inherits dict object and if the key is missing we can give out our custom output.

--

--

Rami Louhibi
Rami Louhibi

No responses yet