class HelloTest(unittest.TestCase): def setUp(self): self.x = Hello(88) def testm(self): self.assertEqual() def testm1(self): self.sum = 12 self.assertTrue(self.x.b(88)) self.assertFalse(self.x.a(89))
def main(): print("This is the test of test() in hello.py: ") hello.test() print("This is the test of main() in hello.py: ") hello.main() print("This is the test of class Hello in hello.py: ") tmp = hello.Hello() tmp.show_string() print("This is the test of class Hello via \"from hello import Hello\"") tmp = Hello() tmp.show_string()
def do_test(): import TWebsocketClient transport = TWebsocketClient.TWebsocketClient("ws://localhost:8888/thrift") protocol = TJSONProtocol(transport) client = Hello.Client(protocol) transport.open() print client.sayHello() transport.close()
def run(): handler = HelloHandler() processor = Hello.Processor(handler) pfacotry = TBinaryProtocol.TBinaryProtocolFactory() server = THttpServer.THttpServer(processor, ('127.0.0.1', 9090), pfacotry) print "starting server" server.serve() print "done"
def do_test(): transport = THttpClient.THttpClient('http://localhost:9090') transport = TTransport.TBufferedTransport(transport) protocol = TJSONProtocol.TJSONProtocol(transport) client = Hello.Client(protocol) transport.open() print "server response:", client.sayHello() transport.close()
def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['FLASK_APP_USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['FLASK_APP_PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in %s' % Hello().say()) return redirect(url_for('show_entries')) return render_template('login.html', error=error)
def run(): handler = HelloHandler() processor = Hello.Processor(handler) transport = TSocket.TServerSocket('127.0.0.1', 9090) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print "starting server" server.serve() print "done"
class BasicTestCase(unittest.TestCase): def setUp(self): self.hello = Hello() def testHelloString(self): """Check that the default hello world string is present.""" assert (str(self.hello) == "Hello, World!") def testChangeHelloString(self): """Check that the hello world string changes when the name is changed.""" self.hello.name = "Planet" assert (str(self.hello) == "Hello, Planet!") def testEmptyName(self): """Check that the greeting is just "Hello!" if the name is an empty string.""" if not self.hello.name: assert (str(self.hello) == "Hello!") def testAdd(self): self.hello.add("Zozo") assert ("Zozo" in self.hello.name_list()) def testPickRandom(self): self.hello.pick_random() assert (self.hello.name in self.hello.name_list())
def main(): transport = TSocket.TSocket('127.0.0.1', 9090) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Hello.Client(protocol) transport.open() print client.hello_string('string') print client.hello_int(123) print client.hello_boolean(True) print client.hello_void() print client.hello_null() transport.close()
def main(): handler = HelloHandler() processor = Hello.Processor(handler) pfactory = TJSONProtocolFactory() application = tornado.web.Application([ (r"/thrift", ThriftWSHandler, dict(processor=processor, inputProtocolFactory=pfactory, outputProtocolFactory=pfactory)) ]) application.listen(8888) tornado.ioloop.IOLoop.instance().start()
class HelloLibrary: """ Hello Library to *Hello* with name Calling from ``set_name`` method """ def __init__(self): self._hello = Hello() self._result = '' @keyword('Try to say hi with') def say_hi(self, name): """ Say hi with name Examples: | Say hi | name 1 | | Say hi | name 2 | """ self._hello.set_name(name) logger.console('Say hi with %s' %(name)) def result_should_be(self, expected): """ Verifies that the current result is ``expected``. Examples: | Result Should Be | Hi, name 1 | | Result Should Be | Hi, name 2 | """ if self._hello.get_result() != expected: raise AssertionError('%s != %s' % (self._result, expected)) def say_hi2(self, name='no name 1', name2='no name 2'): self._hello.set_name(name) def say_hi_all(self, **names): for name, value in names.items(): print('%s = %s' % (name, value))
def should_have_executed(monkeypatch) -> None: def mock_init(*args: tuple, **kwargs: dict) -> None: assert args[1] == ['on'] execute_calls = [] monkeypatch.setattr(f"{MODULE_NAME}.Bluetooth.__init__", mock_init) monkeypatch.setattr(f"{MODULE_NAME}.Bluetooth.execute", lambda *a, **k: execute_calls.append('')) monkeypatch.setattr(f"{MODULE_NAME}.Wifi.__init__", mock_init) monkeypatch.setattr(f"{MODULE_NAME}.Wifi.execute", lambda *a, **k: execute_calls.append('')) mute_logs(MODULE_NAME, monkeypatch) assert Hello().execute() == '' assert len(execute_calls) == 2
def main(): # Make socket transport = TSocket.TSocket('localhost', 5000) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder client = Hello.Client(protocol) # Connect! transport.open() print(client.ping())
def hello(event, context): result = Hello.runHello('hey') try: response = { "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": 'OPTIONS, GET', }, # "body": json.dumps(result, ensure_ascii=False, indent='\t') "body": result } except KeyError: response = { "statusCode": 400, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": 'OPTIONS, GET', }, "body": "400 Bad request" } return response
def __init__(self, manager): monome.Page.__init__(self, manager) Hello.__init__(self)
def make_widgets(self): # extend superclass method Hello.make_widgets(self) extra = Button(self, text='Goodbye', command=self.really_quit) extra.pack(side=RIGHT)
# -*- coding: utf-8 -*- from hello import Hello h = Hello() h.hello('Shane') print(type(Hello)) print(type(h)) def fn(self, name='World'): print('Hello, %s' % name) Hello = type('Hello', (object, ), dict(hello2=fn)) #创建Hello class h = Hello() h.hello2()
from hello import Hello h = Hello() print(h) def fn(self, name='world'): # 先定义函数 print('Hi, %s.' % name) Hi = type('Hi', (object, ), dict(hello=fn)) hi = Hi() hi.hello()
def main(): h = Hello() h.hello()
def __init__(self, app): monome.Page.__init__(self, app) Hello.__init__(self)
def ready(self): monome.Page.ready(self) Hello.ready(self)
def really_quit(self): Hello.quit(self)
# -*- coding: utf-8 -*- # type() # 动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的 # 写一个hello.py模块: class Hello(object): def hello(self, name = 'world'): print('Hello, %s.' % name) from hello import Hello # Python解释器载入hello模块 h = Hello() h.hello() # Hello world print(type(Hello)) # <class 'type'> print(type(h)) # <class 'hello.Hello'> # type()函数可以查看一个类型或变量的类型 # type()函数既可以返回一个对象的类型,又可以创建出新的类型 # 我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义: def fn(self, name = 'world'): # 先定义函数 print('Hello, %s.' % name) Hello type('Hello', (object,), dict(hello = fn)) # 创建Hello class # 创建class对象时,type()函数依次传入3个参数: # 1.class的名称 # 2.继承的父类集合,注意python支持多重继承!只有一个父类,使用tuple单元素写法:必须加个逗号,即使只有一个值:(object, ) # 3.class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上 # 通过type()函数创建的类和直接写class是完全一样的 # Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class
def make_widgets(self): Hello.make_widgets(self) extra = Button(self, text = 'Bye', command = self.really_quit) extra.pack(side=RIGHT)
if __name__ == '__main__': #命令行模式下才会运行下面的代码 test() print sys.argv[0] print u'------------------------2. 别名-----------------------------' #导入模块时,还可以使用别名,这样,可以在运行时根据当前环境选择最合适的模块。 #比如Python标准库一般会提供StringIO和cStringIO两个库,这两个库的接口和功能是一样的, #但是cStringIO是C写的,速度更快,所以,你会经常看到这样的写法: try: import cStringIO as StringIO except importError: # 导入失败会捕获到ImportError import StringIO #这样就可以优先导入cStringIO。如果有些平台不提供cStringIO,还可以降级使用StringIO。 #导入cStringIO时,用import ... as ...指定了别名StringIO,因此,后续代码引用StringIO即可正常工作。 #还有类似simplejson这样的库,在Python 2.6之前是独立的第三方库,从2.6开始内置,所以,会有这样的写法: try: import json # python >= 2.6 except ImportError: import simplejson as json # python <= 2.5 print u'------------------------3. 导入自定义模块-----------------------------' from hello import Hello #导入hello模块的Hello h = Hello() h.hello()
transport = TTransport.TBufferedTransport(transport) protocol = TJSONProtocol.TJSONProtocol(transport) client = Hello.Client(protocol) transport.open() print "server response:", client.sayHello() transport.close() if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'test': do_test() sys.exit(0) handler = HelloHandler() processor = Hello.Processor(handler) #transport = TSocket.TServerSocket(host='127.0.0.1', port=9090) tfactory = TTransport.TBufferedTransportFactory() pfactory = TJSONProtocol.TJSONProtocolFactory() #server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) host = 'localhost' port = 9090 server = MyTHttpServer(processor, (host, port), pfactory) # You could do one of these for a multithreaded server # server = TServer.TThreadedServer( # processor, transport, tfactory, pfactory) # server = TServer.TThreadPoolServer( # processor, transport, tfactory, pfactory)
from sys import exit from tkinter import * # get Tk widget classes from hello import Hello # get the subframe class parent = Frame(None) # make a container widget parent.pack() Hello(parent).pack(side=RIGHT) # attach Hello instead of running it Button(parent, text='Attach', command=exit).pack(side=LEFT) parent.mainloop()
#!/usr/bin/env python # -*- coding: utf-8 -*- print u'-----------------------------使用元类------------------------------' print u'-----------------------------1. 使用 type() 函数动态创建类------------------------------' from hello import Hello #导入hello模块的Hello h = Hello() h.hello() #当Python解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个Hello的class对象,测试如下: print type(Hello) #<type 'type'> print type(h) #<class 'hello.Hello'> #type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类: def fn(self, name='world'): # 先定义函数 print('Hello, %s.' % name) Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class h = Hello() h.hello() #Hello, world. print type(Hello) #<type 'type'> print type(h) #<class '__main__.Hello'> #要创建一个class对象,type()函数依次传入3个参数: #1. class的名称; #2. 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法; #3. class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
from hello import Hello from world import World hello_world = Hello(World()) hello_world.say_something() hello_world_second = Hello(World()) hello_world_second.say_something()
def test_hey(self): h = Hello() res = h.hey() print(res) assert res == 'mock'
# -*- coding: utf-8 -*- from number import NumberInt, NumberFloat from hello import Hello h = Hello() h.sayHello() i1 = NumberInt(); f1 = NumberFloat(); i2 = NumberInt(1); f2 = NumberFloat(1.0); i1.printValue() i2.printValue() f1.printValue(); f2.printValue(); # petit test avec les datas... i1.setData("One","Un"); i1.setData("Car","Véhicule de type automobile"); print("getData('Car') = "), print(i1.getData("Car")); print("getData('One') = "), print(i1.getData("One")); print("====== printDatas() ======="); i1.printDatas();
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hello import Hello h = Hello() h.Hi() print(type(Hello), type(h)) # function type() create class Hello def Bye(self, name='world'): print("Bye %s." % name) Byebye = type("BB", (object, ), dict(ByeBye=Bye)) # type('class name', father(tuple), method name & function) b = Byebye() b.ByeBye() print(type(Byebye), type(b)) # class 'type', class '__main__.BB' # same as import class class ListMetaclass(type): # necessary, original from type def __new__(cls, name, bases, attrs): attrs['add'] = lambda self, value: self.append(value) return type.__new__(cls, name, bases, attrs) class MyList(list, metaclass=ListMetaclass): pass
元类 动态语言 函数和类的定义,不是编译时定义的,而是运行时动态创建的 hello.py模块: class Hello(object): def hello(self, name='world'): print('Hello, %s.' % name) 当Python解释器载入hello模块时 会执行该模块的所有语句 动态创建出一个Hello的class对象 from hello import Hello h = Hello() h.hello() Hello, world. print(type(Hello)) #Hello是一个class,它的类型就是type <class 'type'> print(type(h)) <class 'hello.Hello'> class的定义是运行时动态创建的 创建class的方法就是使用type()函数 type()函数既可以返回一个对象的类型,又可以创建出新的类型 可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义 def fn(self, name='world'): # 先定义函数
def really_quit(self): Hello.quit(self) # do superclass quit
from hello import Hello f=Hello() f.hello()
from hello import Hello h = Hello() h.hello() print(type(Hello)) print(type(h))
def should_have_printed_usage_instructions(monkeypatch) -> None: print_coloured_calls = [] monkeypatch.setattr(f"{MODULE_NAME}.print_coloured", lambda *a, **k: print_coloured_calls.append('')) Hello().usage() assert len(print_coloured_calls) == 2