2013-6-15 22:24
=======================
=======================
- 彩虹炫 | 编辑 删除Big
- import sys
sys.stdout = object()
def write(data):
doc["console"].value += data
sys.stdout.write = write
- 彩虹炫 | 编辑 删除Big
- Syntax
class Loader:
def __init__(self,url):
self.url = url
def load(self,target):
self.target = target
req = ajax()
req.on_complete = self.fill
req.open('GET',self.url,False)
req.send()
def fill(self,req):
if req.status == 200:
doc[self.target].html = req.text
brython()
def load(url,target):
Loader(url).load(target)
return False
Note the call to brython() in method fill() : it is necessary to run the scripts that might be included in the page body
The code still needs improvement (it should handle the debug level, allow opening a new tab, etc) but you get the idea. This technique can be used in sites using Brython to speed up page loading ; I will try to implement it on the Brython site itself
- 彩虹炫 | 编辑 删除Big
- def foo(x):
for z in range(x):
yield z
gen = foo(15)
for k in gen:
print(k)
I also added the "else" part of "try / except / else"
- 彩虹炫 | 编辑 删除Big
- with is quite often use with open:
with open('filename','r') as f:
dosomething
once out of with scope, file object is closed.
- 彩虹炫 | 编辑 删除Big
- Unlike Python, you can add attributes to objects created by the object() built-in:
x = object()
x.foo = 44
del x.foo
- 彩虹炫 | 编辑 删除Big
- built-ins alert(), confirm(), prompt() correspond to their Javascript equivalents
the ajax() built-in function allows the execution of HTTP requests in Ajax mode
the win keyword is the window (window object in JS) and
doc represents the HTML document (document in JS)
- 彩虹炫 | 编辑 删除Big
- We suppose there is a DIV with id result in the HTML page
def on_complete(req):
if req.status==200 or req.status==0:
doc["result"].html = req.text
else:
doc["result"].html = "error "+req.text
req = ajax()
req.on_complete = on_complete
req.set_timeout(timeout,err_msg)
req.open('POST',url,True)
req.set_header('content-type','application/x-www-form-urlencoded')
req.send(data)
- 彩虹炫 | 编辑 删除Big
- The ajax() built-in function returns an object similar to XMLHttpRequest in Javascript, but its interface is slightly different. It has the following methods
open(method, url, async) : method is the HTTP method used for the request (usually GET or POST), url is the url to call, async is a boolean that indicates whether the call is asynchronous or not
set_header(name, value) : sets the value of the header name
set_timeout(duration, function) : if the query did not return response within duration in seconds, it will cancel the query and execute the function. This function cannot have arguments
send() : send (starts) the request
- 彩虹炫 | 编辑 删除Big
- python 3
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
You can also customize the separator between items, e.g.:
print("There are <", 2**32, "> possibilities!", sep="")
- 彩虹炫 | 编辑 删除Big
- tips:
- global variable: object (e.g., list) or class,
- block: pair of ":" and "pass" (or "#end")
- collect into a class or object the related variables and functions
- 彩虹炫 | 编辑 删除Big
- function closure acts like class.
function closure is good for similar functions with minor changes.
- 彩虹炫 | 编辑 删除Big
- Features of Python:
01. Object-Oriented: heritage, multi-heritage
02. Decorator; function, class; a probe;; @deco(); def test();
13. Iterables, generator (class with YIELD); works with FOR ... IN
14. Exception Handling; try... except;
25. String Formatting; "text" % (values)
26. List Comprehension; [x for x in... if...]
- 彩虹炫 | 编辑 删除Big
- Encapsulation in python:
1. local variables
2. function, class, object; module, directory;
- 彩虹炫 | 编辑 删除Big
- PEP8
_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
__double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.
- 彩虹炫 | 编辑 删除Big
- Python mangles these names with the class name: if class Foo has an attribute named __a, it cannot be accessed by Foo.__a. (An insistent user could still gain access by calling Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.
- 彩虹炫 | 编辑 删除Big
- if the variable name is "__secret" and the class name is "MyClass" you can access it like this on an instance named "var"
var._MyClass__secret
The convention to suggest/emulate protection is to name it with a leading underscore: self._protected_variable = 10
- 彩虹炫 | 编辑 删除Big
- Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.
- 彩虹炫 | 编辑 删除Big
- __foo__: this is just a convention, a way for the Python system to use names that won't conflict with user names.
_foo: this is just a convention, a way for the programmer to indicate that the variable is private (whatever that means in Python).
__foo: this has real meaning: the interpreter replaces this name with _classname__foo as a way to ensure that the name will not overlap with a similar name in another class.
No comments:
Post a Comment