• Using Classes In Python - Part 5




    Using the Class in an Application



    Most of the time, you use external classes when working with Python. It isn’t very often that a class exists within the confines of the application file because the application would become large and unmanageable. In addition, reusing the class code in another application would be difficult. The following steps help you use the MyClass class that you created in the previous section.

     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:

    import MyClass

    SamsRecord = MyClass.MyClass()
    AmysRecord = MyClass.MyClass("Amy", 44)

    print(SamsRecord.GetAge())
    SamsRecord.SetAge(33)

    print(AmysRecord.GetName())
    AmysRecord.SetName("Aimee")

    print(SamsRecord)
    print(AmysRecord)

    The example code begins by importing the MyClass module. The module name is the name of the file used to store the external code, not the name of the class. A single module can contain multiple classes, so always think of the module as being the actual file that is used to hold one or more classes that you need to use with your application.

    After the module is imported, the application creates two MyClass objects. Notice that you use the module name first, followed by the class name. The first object, SamsRecord, uses the default settings. The second object, AmysRecord, relies on custom settings.

    Sam has become a year old. After the application verifies that the age does need to be updated, it updates Sam’s age.

    Somehow, HR spelled Aimee’s name wrong. It turns out that Amy is an incorrect spelling. Again, after the application verifies that the name is wrong, it makes a correction to AmysRecord. The final step is to print both records in their entirety.

     Choose RunRun Module.

    The application displays a series of messages as it puts MyClass through its paces. At this point, you know all the essentials of creating great classes.


    Extending Classes to Make New Classes


    As you might imagine, creating a fully functional, production-grade class (one that is used in a real-world application actually running on a system that is accessed by users) is time consuming because real classes perform a lot of tasks. Fortunately, Python supports a feature called inheritance. By using inheritance, you can obtain the features you want from a parent class when creating a child class. Overriding the features that you don’t need and adding new features lets you create new classes relatively fast and with a lot less effort on your part. In addition, because the parent code is already tested, you don’t have to put quite as much effort into ensuring that your new class works as expected. The following sections show how to build and use classes that inherit from each other.


     

    Building the child class


    Parent classes are normally supersets of something. For example, you might create a parent class named Car and then create child classes of various car types around it. In this case, you build a parent class named Animal and use it to define a child class named Chicken. Of course, you can easily add other child classes after you have Animal in place, such as a Gorilla class. However, for this example, you build just the one parent and one child class, as shown in Listing 14-2.

    Listing 14-2:  Building a Parent and Child Class

    class Animal:
    def __init__(self, Name="", Age=0, Type=""): self.Name = Name
    self.Age = Age self.Type = Type

    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 GetType(self): return self.Type

    def SetType(self, Type): self.Type = Type

    def __str__(self):

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


    class Chicken(Animal):

    def __init__(self, Name="", Age=0): self.Name = Name
    self.Age = Age self.Type = "Chicken"

    def SetType(self, Type):
    print("Sorry, {0} will always be a {1}"
    .format(self.Name, self.Type))

    def MakeSound(self):
    print("{0} says Cluck, Cluck, Cluck!".format(self.Name))


    The Animal class tracks three characteristics: Name, Age, and Type. A production application would probably track more characteristics, but these characteristics do everything needed for this example. The code also includes the required accessors for each of the characteristics. The __str__() method completes the picture by printing a simple message stating the animal characteristics.


    The Chicken class inherits from the Animal class. Notice the use of Animal in parentheses after the Chicken class name. This addition tells Python that Chicken is a kind of Animal, something that will inherit the characteristics of Animal.

    Notice that the Chicken constructor accepts only Name and Age. The user doesn’t have to supply a Type value because you already know that it’s a chicken. This new constructor overrides the Animal constructor. The three attributes are still in place, but Type is supplied directly in the Chicken constructor.

    Someone might try something funny, such as setting her chicken up as a gorilla. With this in mind, the Chicken class also overrides the SetType() setter. If someone tries to change the Chicken type, that user gets a message rather than the attempted change. Normally, you handle this sort of problem by using an exception, but the message works better for this example by making the coding technique clearer.


    Finally, the Chicken class adds a new feature, MakeSound(). Whenever someone wants to hear the sound a chicken makes, he can call MakeSound() to at least see it printed on the screen.


    Testing the class in an application


    Testing the Chicken class also tests the Animal class to some extent. Some functionality is different, but some classes aren’t really meant to be used. The Animal class is simply a parent for specific kinds of animals, such as Chicken. The following steps demonstrate the Chicken class so that you can see how inheritance works.
     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:

    import Animals

    MyChicken = Animals.Chicken("Sally", 2) print(MyChicken) MyChicken.SetAge(MyChicken.GetAge() + 1) print(MyChicken) MyChicken.SetType("Gorilla") print(MyChicken)
    MyChicken.MakeSound()

    The first step is to import the Animals module. Remember that you always import the filename, not the class.

    The example creates a chicken, MyChicken, named Sally, who is age 2. It then starts to work with MyChicken in various ways. For example, Sally has a birthday, so the code updates Sally’s age by 1. Notice how the code combines the use of a setter, SetAge(), with a getter, GetAge(), to perform the task. After each change, the code displays the resulting object values for you. The final step is to let Sally say a few words.

     Choose RunRun Module.


    You see each of the steps used to work with MyChicken. As you can see, using inheritance can greatly simplify the task of creating new classes when enough of the classes have commonality so that you can create a parent class that contains some amount of the code.
  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts