• No results found

Class Instances

In document Making Use of Python (Page 185-190)

Other than attribute referencing, the operation that you can perform with classes is cre- ating an instance of a class. A class instance is a variable that contains a reference to the class, which is of a data structure definition type. All instances are of the type, instance. In Python, it is easier to create an instance in comparison to other object-oriented lan- guages. The process of creating an instance of a class is known as instantiation.

Class instantiation uses the function notation to call a class object, which creates an empty object. This object is then assigned to a local variable called the instance. Take the example of the class, My_Class, created earlier. Let’s create a new instance of My_Classand assign the object to the variable, m.

>>>m = My_Class()

Now that you know about class instances, let’s learn to work with functional attributes.

Functional Attributes

As discussed earlier, class attributes are of two types, data attributes and functional attributes. Functional attributes or method class attributes are the methods of a class. Working with functional attributes generally involves method handling. As methods are the functions defined in a class, they are defined as part of the class definition and are invoked by instances.

Python uses the concept of binding to restrict method calls by using only a class instance. Binding requires a method to be bound to an instance before you can call the method. Even if a method cannot be called directly by using the class object, it is still an attribute of the class in which it is defined. A method is considered bound if the instance is present and unbound if the instance is not present.

Let’s consider an example to explain this concept. First, a new class, My_Method_Class, will be defined. This class will include a method, my_method_example. This method will then be called directly as any other function is called.

>>>class My_Method_Class: ... def my_method_example(self):

... return ‘An example of method reference’ ...

>>>my_method_example()

Traceback (most recent call last): File “<pyshell#5>”, line 1, in ?

my_method_example()

NameError: name ‘my_method_example’ is not defined

When the my_method_example is called directly, the attempt fails and a NameErrorexception is raised. If the method is called by using the class object, it raises the TypeError exception. Let’s try this:

>>>My_Method_Class.my_method_example() Traceback (most recent call last):

File “<pyshell#6>”, line 1, in ? My_Method_Class.my_method_example()

TypeError: unbound method my_method_example() must be called with My_Method_Class instance as first argument (got nothing instead)

In the previous examples, my_method_example is unbound. As it is a method and not a function available in the global namespace, it needs to be bound so that you can invoke it directly.

Let’s now bind the my_method_example method and call it by using the instance of the class, My_Method_Class.

>>>m = My_Method_Class() >>>m.my_method_example()

‘An example of method reference’

In this example, the my_method_example method is bound by creating an instance of the My_Method_Class, m. This instance is then used to call the my_method_examplemethod.

There are situations when you might want to invoke unbound methods. A few of the common reasons for doing so are when you want to apply static methods that are not supported by Python and when a specific instance of the method class is not available. You can call an unbound method by providing the object of the instance explicitly. The following code explains how you can do this.

>>>My_Method_Class.my_method_example(m) ‘An example of method reference’

If the instance object is not available, you will not be able to call an unbound method.

The __init__() Constructor Method

The __init__() constructor is a special method available in Python that can be defined in a class to create objects in the initial state. If the class for which you are cre- ating the instance contains any __init__() method, then it is invoked at the time of instantiation. The class object is returned, and the instantiation process is completed only after the __init__() method has been implemented. The __init__() method should not return any object other than the class object because this might lead to a conflict.

The __init__() method is also commonly used to set instance attributes. Instance attributes are data attributes, which contain values associated with a specific instance of a class. Instance attributes are not declared like local variables. They are set when the __init__()method is implemented at the time of instantiation. Instance attributes are referred to in the same way as any other data attribute.

Let’s look at an example code to define the __init__() method in a class and ini- tialize instance attributes:

def __init__(self): self.a=0 self.b=0

The __init__() special method has self as the first argument like any other function and method defined in Python. During the instantiation operation, when the __init__()method is called, the object of the instance is passed to self. In the pre- ceding example, two instance attributes, a and b, are also initialized. The __init__() method can also have arguments other than self. As the __init__() method is not invoked directly, you can pass values to these arguments through the instantiation operator at the time of instantiation.

Let’s consider an example that will show how differently a class will behave after the __init__() method is defined in it. For this, a new class, My_Init, needs to be created on the basis of My_Class used earlier. Let’s create the My_Init class:

>>>class My_Init:

... ‘An example of __init__ method’ ... def __init__(self, aVal, bVal): ... self.a=aVal ... self.b=bVal ... >>>i = My_Init(1,2) >>>i.a, i.b (1, 2)

In this example, three arguments are defined in the __init__() method, self, aVal, and bVal. During the instantiation operation, the object of the instance is passed to self, and the values for the arguments, aVal and bVal, are passed as part of the class invocation call. The values in aVal and bVal are then assigned to the two instance attributes, which are accessed later. You can use the dir() built-in method and the __dict__ special attribute to display all the instance attributes. Let’s use the previous example and see how it works.

>>>dir(i)

[‘__doc__’, ‘__init__’, ‘__module__’, ‘a’, ‘b’] >>>

>>>i.__dict__ {‘a’: 1, ‘b’: 2}

Python also provides a special destructor method, __del__. Destructors are imple- mented in Python to do some processing after the references to all instance objects are removed and before the instances are deallocated. The __del__ method is not imple- mented commonly because these conditions are difficult to meet.

Result

The library class will contain the following objects: ■■ Attributes

LibCode. This attribute will contain the library code for the book or software.

Title. This attribute will contain the title of the book or the software.

Price. This attribute will contain the price of the book or software. ■■ Methods

init__(). This method is the constructor of the class. It will initialize the attributes defined in it.

def __init__(self):

‘library class constructor’ ...

... ...

lib_method(). This method will prompt the user to enter the item code, the title, and the price of a book or software.

def lib_method(self):

‘Enter common details for books and software’ ...

... ...

empty_file_method(). This method will delete the records of all the books or software.

def empty_file_method(self, FileName): ‘Delete book or software records’ ...

... ...

clear__screen_method(). This method will clear the screen.

def clear_screen_method(self): ‘Clear screen method’ ...

... ...

The books class will contain the following objects: ■■ Attributes

Author. This attribute will contain the name of the author of the book.

PageCount. This attribute will contain the total number of pages in the book.

ISBN. This attribute will contain the International Standard Book Number (ISBN) of the book.

■■ Methods

bks_method(). This method will ensure that the user enters all the details about a book.

def bks_method(self): ‘Enter book details’ ...

... ...

bks_display(). This method will display the details of all the books.

def bks_display(self): ‘Display book details’ ...

... ...

The software class will contain the following objects: ■■ Attributes

ProductOf. This attribute will contain the name of the software company.

Size. This attribute will contain the size of the software. ■■ Methods

sws_method(). This method will ensure that the user enters all the details about the software.

def sws_method(self): ‘Enter software details’ ...

... ...

sws_display(). This method will display the details of all the software.

def sws_display(self):

‘Display software details’ ...

... ...

In document Making Use of Python (Page 185-190)