Python Objects and a Simple Web Server ###################################### .. note:: Learning objectives: Explain the three aspects of object orientation. Start a basic Python web server and explain how it works. Prove comprehension by overwriting the GET method. Objects ======= Objects are a complex data structure that has three attributes: **encapsulation**, **inheritance**, and **polymorphism**. *(These will appear on a test in high school -- I guarantee it.)* * Encapsulation * An object is a container for attributes and methods (functions). * For example, let's say I have a class called *animal* with *class animal:...* * I create an object of that class called *Spot* with *Spot = animal()* . * Spot is now an object of type animal(). This is called **instantiation**. Say it with me. * I set *Spot.legs = 4* and Spot now has an attribute called *legs* which is a variable containing the integer 4. .. code-block:: python >>> class animal: ... pass ... >>> Spot = animal() >>> Spot.legs = 4 >>> Spot.legs 4 >>> Spot.eyes Traceback (most recent call last): File "", line 1, in AttributeError: 'animal' object has no attribute 'eyes' * Inheritance * We can compose objects of other objects. * Let's say I create a class called *dog* which inherits *animal* with *class dog(animal):...* . * Now dog has all of the attributes of animal. We say dog is a **child class** of animal. .. code-block:: python :linenos: class animal: # We will set some animal defaults legs = 4 eyes = 2 claws = False tentacles = False class dog(animal): # Even though you can't see it, dog also has legs # ... and eyes and a few more attributes. tails = 1 claws = True adorable = True name = '' Spot = dog # We instantiate Spot, an object of class dog print(Spot.legs) print(Spot.eyes) print(Spot.tails) * Polymorphism * The language doesn't care where it gets a name for an attribute or method. * In this example, we have a function called *self.istasty()* . * It does something different for dog() than it does for the parent class animal(). .. code-block:: python :linenos: class animal: # We will set some animal defaults legs = 4 eyes = 2 claws = False tentacles = False name = '' edible = True # We assume it's edible def __init__(self, newname=''): if newname: self.setname(newname) while not self.name: self.setname(input('Name this beast: ')) def setname(self, newname): self.name = str(newname) def istasty(self): if self.edible: print("%s is edible. Use BBQ sauce!" % self.name) else: print("Do not eat %s." % self.name) class dog(animal): # Even though you can't see it, dog also has legs # ... and eyes and a few more attributes. tails = 1 claws = True adorable = False edible = False name = '' def __init__(self, newname=''): if newname: self.setname(newname) while not self.name: self.setname(input('Name this doggie: ')) def istasty(self): if self.edible and not self.adorable: print("%s is edible. Use BBQ sauce!" % self.name) elif self.edible and self.adorable: print("%s is edible, but too cute! Do not eat it!" % self.name) else: print("Do not eat %s." % self.name) Bessy = animal('Bessy') Bessy.istasty() Spot = dog('Spot') # We instantiate Spot, an object of class dog Spot.edible = True Spot.adorable = True Spot.istasty() # Notice how self.istasty() has new instructions **Spot is counting on you to get this right. Don't let Spot be food.** .. image:: images/sadpuppy.png .. note:: Notice what happens when you just type *Spot = dog()* . It will make you name your dog. A Basic Web Server ================== Let's create a directory from which we will serve our source code. .. code-block:: bat cd %userprofile% md serverroot cd serverroot Inside that directory, we will place our program, as stolen from https://docs.python.org/3/library/http.server.html .. code-block:: python :linenos: :caption: webserver.py from https://python.org import http.server import os import string # We create an HTTPRequestHandler class that inherits the BaseHTTPRequestHandler # ... and lets us play with its attributes and methods class HTTPServer_RequestHandler(http.server.BaseHTTPRequestHandler): # GET method def do_GET(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type','text/html') self.end_headers() # Send directory listing to the client mydir = string.join(list(os.listdir('.')), '
') message = str('' + mydir + '') self.wfile.write(bytes(message)) return def run(): print('starting server...') server_address = ('', 8008) # a tuple of ip address and port httpd = http.server.HTTPServer(server_address, HTTPServer_RequestHandler) print('Starting!') httpd.serve_forever() run() For more readings on HTTP methods, such as GET and POST, try https://www.w3schools.com/tags/ref_httpmethods.asp .