Presented by Ian Christy Philly Python Workshop http
Presented by Ian Christy
Philly Python Workshop http: //phillypythonworkshop. github. io/saturdaylesson/ Continuing with the State Example
Overview of Python Classes With code example What is a Class ? What is an Object ?
A class is a template The template describes Structure Methods Variables
Python Code class State: """ a State in the United States """ def __init__(self, name , capital): self. name = name self. capital = capital
class State: """ a State in the United States """ def __init__(self, name , capital): self. name = name self. capital = capital
class State: """ a State in the United States """ def __init__(self, name , capital): self. name = name self. capital = capital A function inside a class is known as a method A variable inside a class is known as an Attribute
When you define a class you create a “namespace” >>> print(type(State)) <type 'classobj'> >>> print( id(State)) 34627504
What is a Namespace Think of a namespace as a container or a context environment. It's own little world. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. Names within a namespace must be unique you cannot have two classes or two functions in the same module with the same name as they share the namespace of the module.
Some namespaces in Python: local names in a function or method invocation global names of a module built-in names, this namespace contains built-in functions e. g. abs(), cmp(), min(), next(), float() …
Namespace is a way to implement scope. The scope of a name is the area of a program where this name can be unambiguously used. Scope prevents conflicts between classes, methods and objects with the same name that might have been written by different people. Scope is nested, from local to global. Each variable name is checked first in the local namespace and then checked in the global namespace. Variables are generally created only in a local namespace.
Lifetime of a Namespace When a function, method function, module or package is evaluated (that is, starts execution) a namespace is created. When a function or method function finishes execution, the namespace is dropped. The variables are dropped. any objects in that namespace will also be dropped.
More on Namespaces: http: //www. python-course. eu/namespaces. php http: //www. pythoncourse. eu/python 3_class_and_instance_attributes. php Eric Snow presentation on youtube https: //www. youtube. com/watch? v=t. Apw. Hox. AEQI
Lets Create Some Objects !! Create a specific object from a class template This is called Instantiation
Alaska = State('Alaska', 'Juneau') Now you have an object in memory. >>> print(type(Alaska)) <type 'instance'> >>> print( id(Alaska)) 359493576
How to reference variables in object: print(Alaska. name) Alaska print(Alaska. capital) Juneau
Why would we use a class and it’s object ? What do they do for me ? How do they make my programming life easier?
We can easily add attributes (variables) class State: def __init__(self, name , capital): self. name = name self. capital = capital self. flower = "" self. motto = "" self. population = "" self. size = "" self. governor = ""
How to set the new variables Alaska. flower = 'Myosotis alpestris' Alaska. motto = 'North to the future' Alaska. population = 736732 Alaska. size Alaska. governor = '663, 300 square miles' = 'Bill Walker'
Lets Print our object: print(Alaska) <__main__. State instance at 0 x 1 cac 9 fc 8>
There are some special methods for python classes def __str__(self): P 2 P 3 return self. capital + " is the capital of " + self. name return "{} is the capital of {} " . format(self. name, self. capital) print(Alaska) Juneau is the capital of Alaska
The Real Power of classes You can create your own Methods
We can easily add our own methods class State: def __init__(self, name , capital): self. name = name self. capital = capital def test_capital(self, v_str): if v_str == self. capital: return True else: return False
If Alaska. test_capital(“Harrisburg”): print(‘You are correct’) else: print(‘Nope’)
The concept of Inheritance You create a general class ABC – Abstract Base Class example: Vehicle then you create classes for: class Car(Vehicle) class Truck(Vehicle) class Motorcycle(Vehicle) https: //www. jeffknupp. com/blog/2014/06/18/improve-yourpython-classes-and-object-oriented-programming/
Lets imagine you wanted to create a game where you can move from one State to any adjoining State. The rule is you can only move into an adjoining state, no hopping. You have to correctly pick a neighbor state to move into the next state. When you enter a state you automatically collect that states flower. The goal is to collect more state flowers than other players. How would you code this ?
Some of the things you will need: Database list of states state flower list of neighboring states Enhance the class State add variable flower add variable neigbhor add method move_to_neighbor cur_state – instance of State players list of flowers my_vase: []
In your class define a variable to hold the list of adjoining states. class State: """ a state in the United States """ def __init__(self, name, capital): self. name = name self. capital = capital self. flower = "" self. neighbors = []
Define a method about moving def move_to_neighbor( new_state): if new_state in cur_state. neighbors: return OK_TO_GO else: return NO_GO For each object define the neighbors for each State: Alaska. neighbors = [‘Washington’, ’Hawaii’] pull neighbors from database
Move to the next state: give user list of states; one or more may be a neighbor. Test users choice If cur_state. move_to_neighbor( new_state ): print(‘you have moved to {}’. format( add_flower( new_state ) print(‘you now have {} flowers’. format( else: print(‘sorry not a neighbor’)
keep count of number of flowers in players basket. How to end the game; if user has hit all 50 states add code to not add a state flower twice if user fails 3 x to get neighbor correct on exit give the user his score
- Slides: 32