• Using Classes In Python - Part 3



    Working with constructors

     

    A constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class. Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts. Constructors can also verify that there are enough resources for the object and perform any other start-up task you can think of.


    The name of a constructor is always the same, __init__(). The constructor can accept arguments when necessary to create the object. When you create a class without a constructor, Python automatically creates a default constructor for you that doesn’t do anything. Every class must have a constructor, even if it simply relies on the default constructor. The following steps demonstrate how to create a constructor:


    Open a Python Shell window.

    You see the familiar Python prompt.

    Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

    class MyClass: Greeting = ""

    def __init__(self, Name="there"): self.Greeting = Name + "!"

    def SayHello(self):
    print("Hello {0}".format(self.Greeting))

    This example provides your first example of function overloading. In this case, there are two versions of __init__(). The first doesn’t require any special input because it uses the default value for the Name of "there". The second requires a name as an input. It sets Greeting to the value of this name, plus an exclamation mark.

    Python doesn’t support true function overloading. Many strict adherents to strict Object-Oriented Programming (OOP) principles consider default values to be something different from function overloading.

    However, the use of default values obtains the same result, and it’s the only option that Python offers. In true function overloading, you see multiple copies of the same function, each of which could process the input differently.

     Type MyInstance = MyClass( ) and press Enter.

    Python creates an instance of MyClass named MyInstance.

     Type MyInstance.SayHello( ) and press Enter.

    Notice that this message provides the default, generic greeting.

     Type MyInstance = MyClass(“Amy”) and press Enter. Python creates an instance of MyClass named MyInstance.

     Type MyInstance.SayHello( ) and press Enter.

    Notice that this message provides a specific greeting.

     Close the Python Shell window.

    Working with variables


    As mentioned earlier in the book, variables are storage containers that hold data. When working with classes, you need to consider how the data is stored and managed. A class can include both class variables and instance variables. The class variables are defined as part of the class itself, while instance variables are defined as part of methods. The following sections show how to use both variable types.

     

    Creating class variables


    Class variables provide global access to data that your class manipulates in some way. In most cases, you initialize global variables using the constructor to ensure that they contain a known good value. The following steps demonstrate how class variables work.

     Open a Python Shell window.

    You see the familiar Python prompt.

     Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

    class MyClass: Greeting = ""

    def SayHello(self):
    print("Hello {0}".format(self.Greeting))

    . Normally you do include a constructor to ensure that the class variable is initialized properly. However, this series of steps shows how class variables can go wrong.

     Type MyClass.Greeting = “Zelda” and press Enter.

    This statement sets the value of Greeting to something other than the value that you used when you created the class. Of course, anyone could make this change. The big question is whether the change will take.

     Type MyClass.Greeting and press Enter.

    You see that the value of Greeting has changed.

     Type MyInstance = MyClass( ) and press Enter.

    Python creates an instance of MyClass named MyInstance.

     Type MyInstance.SayHello( ) and press Enter.

    The change that you made to Greeting has carried over to the instance of the class. It’s true
    that the use of a class variable hasn’t really caused a problem in this example, but you can imagine what would happen in a real application if someone wanted to cause problems.

    This is just a simple example of how class variables can go wrong. The two concepts you should take away from this example are as follows:

     Avoid class variables when you can because they’re inherently unsafe.

     Always initialize class variables to a known good value in the constructor code.

     Close the Python Shell window.


    Creating instance variables


    Instance variables are always defined as part of a method. The input arguments to a method are considered instance variables because they exist only when the method exists. Using instance variables is usually safer than using class variables because it’s easier to maintain control over them and to ensure that the caller is providing the correct input. The following steps show an example of using instance variables.


     Open a Python Shell window.

    You see the familiar Python prompt.

     Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

    class MyClass:

    def DoAdd(self, Value1=0, Value2=0): Sum = Value1 + Value2
    print("The sum of {0} plus {1} is {2}."
    .format(Value1, Value2, Sum))

    In this case, you have three instance variables. The input arguments, Value1 and Value2, have default values of 0, so DoAdd() can’t fail simply because the user forgot to provide values. Of course, the user could always supply something other than numbers, so you should provide the appropriate checks as part of your code. The third instance variable is Sum, which is equal to Value1 + Value2. The code simply adds the two numbers together and displays the result.

     Type MyInstance = MyClass( ) and press Enter.

    Python creates an instance of MyClass named MyInstance.

     Type MyInstance.DoAdd(1, 4) and press Enter.

    5. Close the Python Shell window.



  • 0 comments:

    Post a Comment

    Powered by Blogger.

    Tags

    Popular Posts