Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright (c) 2017 by Dr. E. Horvath

Similar presentations


Presentation on theme: "Copyright (c) 2017 by Dr. E. Horvath"— Presentation transcript:

1 Copyright (c) 2017 by Dr. E. Horvath
Classes Classes are an integral part of implementing the object-oriented paradigm which includes encapsulation, polymorphism, and inheritance. Consider the following simple class. Also, note that the naming convention is CapWords; each word in the class name is capitalized and there is no underscore. class PantherClass(object): def __init__(self, type = 0, motto = ' ', creed = ' '): self.type_int = type self.motto_str = motto self.creed_str = creed Copyright (c) 2017 by Dr. E. Horvath

2 Copyright (c) 2017 by Dr. E. Horvath
Classes and Instances A class is a template for an object. The process of creating an object based upon a class is called instantiation. The __init__ constructor is called when a new object is created. Kinds of classes already encountered: string, list, dictionary, and tuple Copyright (c) 2017 by Dr. E. Horvath

3 Copyright (c) 2017 by Dr. E. Horvath
Class Attributes The attributes of a class are its methods and its names of values. A method is similar to a function, and methods will be discussed in more detail on a later slide. Create the following bare-bones class from the shell: class TheClass(object): pass Recall that the keyword pass serves as a placeholder. Now type in dir(TheClass) to the shell; all of the built-in attributes of the class will be listed. Next, create an instance of the class as follows: the_instance1 = TheClass() Type in dir(the_instance1) to the shell and, once again, all of the built-in attributes of the class will be listed. Copyright (c) 2017 by Dr. E. Horvath

4 Copyright (c) 2017 by Dr. E. Horvath
Class Attributes ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] What do these mean? Copyright (c) 2017 by Dr. E. Horvath

5 Adding Attributes to Classes and Instances
From the shell, add an attribute to the instance you just created on the previous slide by typing in the following line: the_instance1.greeting_str = 'Howdy' Now, type in dir(the_instance1) to the shell. The name greeting_str has been added to the list of attributes. However, this attribute has not been added to the class. To check this, type in dir(TheClass) again. Create another instance of TheClass: the_instance2 = TheClass() The new instance also lacks the attribute, greeting_str. Copyright (c) 2017 by Dr. E. Horvath

6 Adding Attributes to Classes and Instances Cont'd
Now add an attribute to the class itself: TheClass.aloha_str = 'Ciao!' Adding an attribute to the class itself will cause the attribute to be added to any instance of that class. Type in dir(TheClass), dir(the_instance1), and dir(the_instance2). Of course, the attribute greeting_str still only is an attribute of the_instance1. Copyright (c) 2017 by Dr. E. Horvath

7 A Method in the Madness Part I
Methods are very much like functions, except that methods are defined inside of the class to which they belong and the first parameter in a method definition must be the self parameter. The self allows the class to reference the object itself. The methods define the behavior of the class. Consider the following class that contains one programmer-defined method: import math class MersenneClass: def search_for_prime(self, n): self.n = n motto_str = "Vive la France!" value = math.pow(2.0, self.n) – 1 # a prime number that is 2^n - 1 div = 3 flag = True while div < int(value/2): if value%div == 0: print(str(int(value))+" is not a prime number. C'est la vie.") print("Divisible by " + str(div)) flag = False break div += 1 if flag: print(str(int(value))+" is a prime number. "+motto_str) return Copyright (c) 2017 by Dr. E. Horvath

8 A Method in the Madness Part II
The following snippet of code creates an instance of the class, and the method calculate_prime(i) is called iteratively. the_Mersenne = MersenneClass() for i in range(2,12): the_Mersenne.search_for_prime(i) When the method calculate_prime is called only one argument is passed to it. However, in the definition of the method calculate_prime there are two parameters, the first of which much be the self parameter. This is so we can reference the object that called the method. You are not limited to calling this parameter self. However, it will make your code harder to understand if you do not follow this convention. (Note that this code is not an efficient way of calculating Mersenne prime numbers.) Copyright (c) 2017 by Dr. E. Horvath

9 A Method in the Madness Part III
Add to the MersenneClass the following method def print_last_n(self): print(“The last n was “+str(self.n)) And following the for loop, add the line the_Mersenne.print_last_n() Notice that no argument is passed to the method. However, the parameter self appears in the definition of the method. This is how we are able to reference the quantity n, the value of which was set the last time the method search_for_prime was called. If you attempt to access the value of n without using self.n, a NameError will be thrown. Copyright (c) 2017 by Dr. E. Horvath

10 Copyright (c) 2017 by Dr. E. Horvath
The __init__ method The __init__ method is a special method that is called only once and it is called automatically when an instance is created. This is why it is called a constructor. The init method allows you to add attributes to the class. On the previous slide, you saw that the quantity n was not an attribute of either MersenneClass or the_Mersenne print(dir(MersenneClass)) print(dir(the_Mersenne)) In addition to all of the built-in attributes, you'll also see the two methods that belong to MersenneClass. However, notice that the integer n does not appear in that list. Copyright (c) 2017 by Dr. E. Horvath

11 Methods are Attributes
It's instructive to see what attributes MersenneClass and the_Mersenne have. Add the following two lines of code to the bottom of your program. print(dir(MersenneClass)) print(dir(the_Mersenne)) In addition to all of the built-in attributes, you'll also see the two methods that belong to MersenneClass. However, notice that the integer n does not appear in that list. Copyright (c) 2017 by Dr. E. Horvath

12 The __init__ method: An Example
Add the following init method right after class MersenneClass: def __init__(self): self.n = 0 Notice that the attributes of MersenneClass still do not include n, but theMersenne now does. Copyright (c) 2017 by Dr. E. Horvath

13 More on the __init__ method
The __init__ method ensures that every instance has the same attributes. Nevertheless, it is possible to add attributes to an instance as follows theMersenne.excl_str = “VOILA” Adding a return statement at the end of init is not necessary because that is handled automatically. The two underscores that precede and follow init indicate this a special method. If no __init__ method is found then the default instance is returned. Copyright (c) 2017 by Dr. E. Horvath

14 Another __init__ method example
class CarRecord: def __init__(self, make=' ', model=' ', year=' ', owner=' '): self.make = make self.model = model self.year = year self.owner = owner def contact_owner(self, message=' '): pass def main(): car_dict = { } # The dictionary will contain a number of Car Record objects try: owner_response = input("Owner's name: ") while owner_response.lower() != "exit": make_response = input("Make of car: ") model_response = input("Model: ") year_response = input("Year: ") car_dict[owner_response] = CarRecord(make_response, model_response, year_response, owner_response) except KeyboardInterrupt: print("Thank you. Good bye.") print(car_dict) main() Copyright (c) 2017 by Dr. E. Horvath

15 Explanation of previous example
At the top of the program is the class CarRecord which is composed of two methods: the __init__ method and a method which will contain the code to contact the owner. Notice, the __init__ method contains five parameters, the self parameter and four other parameters which are passed to the object when the instance is created. The second method just contains the pass statement because we have not yet decided how to contact the owner; remember the statement pass is just a placeholder. The function main() contains the code that prompts the user for the owner's name and the make, model, and year of the car. Upon reading in all of the information, an instance of the class is created and stored in a dictionary. The owner's name serves as the key. This code is inside of a sentinel control loop which the user exits by typing exit. Pressing ctrl-c causes a KeyboardInterrupt which we handle by placing all of this code inside of a try-except block. Copyright (c) 2017 by Dr. E. Horvath

16 Copyright (c) 2017 by Dr. E. Horvath
The __str__ method Another special method is the __str__ method which allows you to print out a representation of the object. Add the following method to the CarRecord class. def __str__(self): return self.owner+” “+self.make You can design your code to return whatever string you want; the only requirement is that this method return a string. Add the following print statement just after the statement where you add the instance to the dictionary. print(car_dict[owner_response]) Copyright (c) 2017 by Dr. E. Horvath

17 Copyright (c) 2017 by Dr. E. Horvath
Public versus Private Other object-oriented programming languages allow the designer to declare methods and instance variables either public or private. A public declaration means that other programmers are free to alter methods and instance variables. A private declaration means that other programmers cannot alter methods and instance variables. Java, for example, enforces this separation between public and private. However, in Python, all methods and instance variables are public. Python does allow the designer a way to indicate to programmers that methods or instance variables should be treated as private. This is done by preceding the instance variable name or method by two underscores. Copyright (c) 2017 by Dr. E. Horvath


Download ppt "Copyright (c) 2017 by Dr. E. Horvath"

Similar presentations


Ads by Google