# -*- coding: utf-8 -*- """ Created on Fri Oct 14 17:45:13 2016
@author: Kirby Urner """ print("{:=^40}".format("< Exhibit 1: scoping controls >")) from random import choice def add_tricks(cls): """ choice(tricks) maintains access to add_tricks namespace, what's known as a "closure" (like a "bottled" space) cls.tricks = [...] would also work """ tricks = ["play dead", "roll over", "sit up"] def do_trick(self): return choice(tricks) cls.do_trick = do_trick return cls @add_tricks class Animal: """ Decorate a class with a function, end up with a new second inheritable method """ def __init__(self, nm): self.name = nm class Mammal(Animal): """Lets teach an old dog some new tricks... """ pass # Animal = add_tricks(Animal) <-- 'no decorator' alternative obj_1 = Animal("Rover") print(obj_1.name, "does this trick:", obj_1.do_trick()) obj_2 = Mammal("Trixy") print(obj_2.name, "does this trick:", obj_2.do_trick()) print("{:=^40}".format("< Exhibit 2: str() vs repr() >")) class Airport: """ Clarifying the relationship between str() & repr() """ def __init__(self, three_letter_code): # birth! self.code = three_letter_code def __str__(self): return "Airport w/ code: " + self.code def __repr__(self): return "Airport('{}')".format(self.code) portland_or = Airport("PDX") newark_nj = Airport("EWR") print(portland_or) # __str__ print(repr(portland_or)) # __repr__ print("{:=^40}".format("< Exhibit 3: scoping controls >")) brand = "Cheery Deary" # who can overwrite def outer(): brand = "Deco Echo" def inner(): # global brand nonlocal brand # reference enclosing scope brand = "Oompa Loompa" # could be local print("inner:",brand) inner() print("outer:",brand) outer() print("Global:", brand)
_______________________________________________ Edu-sig mailing list Edu-sig@python.org https://mail.python.org/mailman/listinfo/edu-sig