• Using Classes In Python - Part 4

     

    Using methods with variable argument lists


    Sometimes you create methods that can take a variable number of arguments. Handling this sort of situation is something Python does well. Here are the two kinds of variable arguments that you can create:

     *args: Provides a list of unnamed arguments.

     **kwargs: Provides a list of named arguments.

    The actual names of the arguments don’t matter, but Python developers use *args and **kwargs as a convention so that other Python developers know that they’re a variable list of arguments. Notice that the first variable argument has just one asterisk (*) associated with it, which means the arguments are unnamed. The second variable has two asterisks, which means that the arguments are named. The following steps demonstrate how to use both approaches to writing an application.
     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    class MyClass:
    def PrintList1(*args):
    for Count, Item in enumerate(args): print("{0}. {1}".format(Count, Item))

    def PrintList2(**kwargs):
    for Name, Value in kwargs.items(): print("{0} likes {1}".format(Name, Value))

    MyClass.PrintList1("Red", "Blue", "Green")
    MyClass.PrintList2(George="Red", Sue="Blue",
    Zarah="Green")

    For the purposes of this example, you’re seeing the arguments implemented as part of a class method. However, you can use them just as easily with an instance method.

    Look carefully at PrintList1() and you see a new method of using a for loop to iterate through a list. In this case, the enumerate() function outputs both a count (the loop count) and the string that was passed to the function.


    The PrintList2() function accepts a dictionary input. Just as with PrintList1(), this list can be any length. However, you must process the items() found in the dictionary to obtain the individual values.

     Choose RunRun Module.

    The individual lists can be of any length. In fact, in this situation, playing with the code to see what you can do with it is a good idea. For example, try mixing numbers and strings with the first list to see what happens. Try adding Boolean values as well. The point is that using this technique makes your methods incredibly flexible if all you want is a list of values as input.


    Overloading operators


    In some situations, you want to be able to do something special as the result of using a standard operator such as add (+). In fact, sometimes Python doesn’t provide a default behavior for operators because it has no default to implement. No matter what the reason might be, overloading operators makes it possible to assign new functionality to existing operators so that they do what you want, rather than what Python intended. The following steps demonstrate how to overload an operator and use it as part of an application.


     Open a Python File window.

    You see an editor in which you can type the example code.


     Type the following code into the window — pressing Enter after each line:

    class MyClass:
    def __init__(self, *args): self.Input = args

    def __add__(self, Other): Output = MyClass()

    Output.Input = self.Input + Other.Input return Output

    def __str__(self): Output = ""

    for Item in self.Input: Output += Item Output += " "
    return Output

    Value1 = MyClass("Red", "Green", "Blue")
    Value2 = MyClass("Yellow", "Purple", "Cyan")
    Value3 = Value1 + Value2

    print("{0} + {1} = {2}"
    .format(Value1, Value2, Value3))

    The example demonstrates a few different techniques. The constructor, __init__(), demonstrates a method for creating an instance variable attached to the self object. You can use this approach to create as many variables as needed to support the instance.

    When you create your own classes, no + operator is defined until you define one, in most cases. The only exception is when you inherit from an existing class that already has the + operator defined. In order to add two MyClass entries together, you must define the __add__() method, which equates to the + operator.

    The code used for the __add__() method may look a little odd, too, but you need to think about it one line at a time. The code begins by creating a new object, Output, from MyClass. Nothing is added to Output at this point — it’s a blank object. The two objects that you want to add, self.Input and Other.Input, are actually tuples. The code places the sum of these two objects into Output.Input. The __add__() method then returns the new combined object to the caller.

    Of course, you may want to know why you can’t simply add the two inputs together as you would a number. The answer is that you’d end up with a tuple as an output, rather than a MyClass as an output. The type of the output would be changed, and that would also change any use of the resulting object.

    To print MyClass properly, you also need to define a __str__() method. This method converts a MyClass object into a string. In this case, the output is a space-delimited string (in which each of the items in the string is separated from the other items by a space) containing each of the values found in self.Input. Of course, the class that you create can output any string that fully represents the object.

    The main procedure creates two test objects, Value1 and Value2. It adds them together and places the result in Value3. The result is printed onscreen.

     Choose RunRun Module.

    Adding the two objects together, converting them to strings, and then printing the result. It’s a lot of code for such a simple output statement, but the result definitely demonstrates that you can create classes that are self-contained and fully functional.

    Creating a Class


    All the previous material in this Post has helped prepare you for creating an interesting class of your own. In this case, you create a class that you place into an external module and eventually access within an application. Listing 14-1 shows the code that you need to create the class.


    Listing 14-1:  Creating an External Class

    class MyClass:
    def __init__(self, Name="Sam", Age=32): self.Name = Name
    self.Age = Age

    def GetName(self): return self.Name

    def SetName(self, Name): self.Name = Name

    def GetAge(self): return self.Age

    def SetAge(self, Age): self.Age = Age

    def __str__(self):

    return "{0} is aged {1}.".format(self.Name, self.Age)


    In this case, the class begins by creating an object with two instance variables: Name and Age. If the user fails to provide these values, they default to Sam and 32.


    This example provides you with a new class feature. Most developers call this feature an accessor. Essentially, it provides access to an underlying value. There are two types of accessors: getters and setters. Both GetName() and GetAge() are getters. They provide read-only access to the underlying value. The SetName() and SetAge() methods are setters, which provide write-only access to the underlying value. Using a combination of methods like this allows you to check inputs for correct type and range, as well as verify that the caller has permission to view the information.


    As with just about every other class you create, you need to define the __str__() method if you want the user to be able to print the object. In this case, the class provides formatted output that lists both of the instance variables.
  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts