Python Programming – Class Object

In this Page, We are Providing Python Programming – Class Object. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Class Object

Class object

When a class definition is created, a “class object” is also created. The class object is basically a wrapper around the contents of the namespace created by the class definition. Class object support two kinds of operations: “attribute reference” and “instantiation”.

Attribute reference

Attribute references use the standard syntax used for all attribute references in Python: obj .name. Valid attribute names are all the names that were in the class’s namespace, when the class object was created. So, if the class definition looked like this:

>>> class MyClass: 
. . .            " " "A simple example class " " " 
. . .           i=12345
. . .           def f ( self ) : 
. . .                 return ' hello world ' :
. . . 
>>> MyClass . i 
12345
>>> MyClass.___doc___
' A simple example class '

then MyClass . i and MyClass . f are valid attribute references, returning an integer and a method object, respectively. The value of MyClass.i can also be change by assignment. The attribute ___doc___is also a valid attribute, returning the docstring belonging to the class.

>>> type ( MyClass )
<type ' classobj ' >

From the above expression, it can be noticed that MyClass is a class object.

Instantiation

A class object can be called to yield a class instance. Class instantiation uses function notation. For example (assuming the above class MyClass):

x=MyCiass ( )

creates a new instance of the class MyClass, and assigns this object to the local variable x.

>>> type ( MyClass( ) )
<bype ' instance' > 
>>> type (x) 
<type 'instance'>

Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ___init___( ), like this:

def __init__ ( self ) :
self.data=[ ]

When a class defines an __init__ ( ) method, class instantiation automatically invokes __init__( ) for the newly created class instance. So in this example, a new, initialized instance can be obtained by:

x=MyClass ( )

Of course, the ___init___ ( ) method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to ___init___ ( ). For example,

>>> class Complex:
. . .          def __init___ ( self , realpart , imagpart ) :
. . .              self . r=realpart
. . .              self . i=imagpart
>>> x=Complex ( 3 . 0, -4 . 5 )
>>> x . r , x . i
( 3 . 0 , -4 . 5 )

Leave a Comment