Python programming language is an object oriented language. Python has builtin classes and one can also create user defined classes.

The int, float, string, list, dictionary are builtin classes. These builtin classes have their own builtin attributes. A string class attribute cannot be applied to list object. If we type x = 9, then x is a named identifier to the object 9 which belongs to class int. Similarly if we type in x = 9.87 then 9.87 is an object which belongs to float class. If we have a string declaration such as s = "my string" then my string is an object that belongs to class str. List object is declared using the square bracket [], dictionary object is declared using the {} and tuple object is declared using parenthesis( ).

Thus each object such as 9, 9.87, "my string", [4,3,7,9], {"name":"john", "age": 25}, (2, 5, 3) belongs to class int, float, str, list, dict, tuple respectively. Each class have their own attributes. One cannot use the attribute of one class to another because the object using the attribute must belong to the class where the attribute is defined.

For example, sort( ) method which belongs to the list class cannot be used by object of the class string. Doing so we will get error. This is illustrated below.

For example, consider the list as follows:

>>> L = [4,2,6,8,3]

sort( ) is an attribute of class list. L is the named identifier of an object that belongs to the class list. There we can use the sort( ) method.

>>> L.sort()
>>> L
[2, 3, 4, 6, 8]

Consider now a string, s, as follows:

>>> s = "my string"

We cannot use the sort( ) attribute because it belongs to list class. Thus we get error if we use sort for this string.

>>> s.sort()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'sort'

 Similarly you cannot use the string class attribute such as upper( ) to list.

>>> L.upper()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'list' object has no attribute 'upper'

But you can use it for the string objects like s:

>>> s.upper()

The following are builtin classes listed in tabular form:


Post a Comment