An Introduction to Python OOP - Python

A class defines a category of objects in terms of the data it encapsulates and the operations on the data that are allowed by the interface functions. Essentially, a class is a template from which objects can be created.

Each object created from a class is an instance of a class. They all look alike and exhibit a similar behavior.

A class stores object attributes (also known as data members) and the behavior of objects (mostly known as methods). This behavior can be inherited from other (base) classes. The non-method attributes of the class are usually referred to as class members or class attributes so that they are not confused with instance attributes.

Each class has its own namespace in which all the assignments and function definitions occur.

Class Instances

A class instance is a Python object, and similar to every Python object, it has the following properties:

identity, object type, attributes, methods, and value.

I will use the following class definition as the basis for the next explanations. First, let's declare the c class, and then we will create an instance of this class called obj.

>>>class c:
… def __init__(self, value=None):
… self.name = value

>>>obj = c()
>>> obj.name = "Andre"

The identity is the memory location allocated for the object. It can be identified by using the id() function.

>>>id(obj)
6623988

The object type is the object's internal representation. It defines the supported methods and operation for each object. You can use the type() function in order to find out the type of a specific object.

>>>type(obj)
<type 'ínstance'>
>>>type(obj.name)
<type 'string'>

While we're talking about object types, let's take a quick break from the whole class issue and examine the types for Python objects defined in extension modules, which do not necessarily act like classes.

Table belowlists all Python built-in object types defined by the types module. Note that almost all the types shown in this table are unrelated to Python classes.

Built-In Object Types Defined by the types Module

Built-In Object Types Defined by the types ModuleBuilt-In Object Types Defined by the types Module

The attributes and methods of an object are bound properties that must be accessed by putting a dot (.) after the object name.

>>> obj.name
"Andre"

At last, the value of an object is better visualized by an example.

>>> obj.name = "Andre"

The string "Andre" is the value assigned to the name attribute of the object obj.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Python Topics