Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 12

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 12 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 122018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 12)

Developing large and complexapplications in an object-oriented manner is out of the scope of this56APPLICATION BUILDING AND SMS INBOXbook. There is a lot of information about object-oriented programmingin other books and on the web. You may be surprised to see thatexample applications which are used to teach object orientation arenot complex at all with Python and they do not require you to deriveobjects of your own.For our purposes, it is enough to know that some functions createobjects. In Example 11, an Ao lock object is assigned to the variableapp lock.app lock = e32.Ao lock()The object itself contains variables and functions that can beaccessed with the dot notation, for example:app lock.wait()calls the object’s wait() function.

Likewise:appuifw.app.title = u"Hello World"assigns a value to the title variable of the app object in the appuifwmodule. In practice, you can treat objects as if they are modules insidemodules, as the dot notation suggests.In this chapter, you can find many examples of object usage. Youhave already seen the app object which handles the standard userinterface and the Ao lock object which is used to wait for user actions.In practice, everything in Python is an object, including strings, lists andtuples, as well as more specific constructs such as the Inbox object,which is used to access SMS messages.

Objects are so ubiquitous inPython that you use them all the time without even noticing it.4.2.1Application MenuThe application menu provides an easy and familiar way to present a listof available operations to the user. After reading this section, you canstart building useful tools with an application menu, which perform tasksaccording to the user’s requests.Python Language Lesson: tupleA tuple is an immutable list. You can’t add, remove or modify its valuesafter creating it. Tuples are often used to group related values, such asAPPLICATION STRUCTURE57coordinates, address lines or ingredients of a recipe.

Tuples are definedin the same way as lists but, instead of square brackets, values areenclosed in parentheses:red = (255, 0, 0)weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")family = (("Mary", 38), ("John", 35), ("Josephine", 12))The first and second lines define simple sequences. The last linemakes a tuple of tuples. The inner tuples contain different types ofvalue: strings and integers.You can easily unpack values from tuples back to individual variables. Here we use the tuples red and family that were createdabove:r, g, b = redmom, dad, child = familyIn this case, the variables r, g and b are integers and mom, dadand child are two-item tuples. Note that you have to define asmany variables in unpacking as there are items in the correspondingtuple.You may refer to individual items in a tuple with indices, as withlists.

In contrast to lists, assignments such asfamily[1] = ("Jack", 25)are not possible since this would modify the tuple.In some cases you need to convert lists to tuples or tuples to lists. Theformer is possible with function tuple() and the latter with functionlist().

For example:print list(red)puts out a list to your screen:[255, 0, 0]Note the square brackets that denote a list.58APPLICATION BUILDING AND SMS INBOXExample 12 extends Example 11 to include an application menu (seeFigure 4.3).Figure 4.3 Application menuExample 12: Application menuimport appuifw, e32def photo():appuifw.note(u"Cheese!")def darken():appuifw.note(u"I can't see a thing!")def lighten():appuifw.note(u"My eyes are burning!")def quit():print "WANNABE PHOTOEDITOR EXITS"app_lock.signal()appuifw.app.exit_key_handler = quitappuifw.app.title = u"PhotoEditor"appuifw.app.menu = [(u"Take Photo", photo), (u"Edit photo",((u"Darken", darken), (u"Lighten", lighten)))]print "WANNABE PHOTOEDITOR STARTED"app_lock = e32.Ao_lock()app_lock.wait()The application menu, appuifw.app.menu, is defined as a list thatconsists of tuples.

Each item in the list is of the form (u"Item name",APPLICATION STRUCTURE59item handler), where the first element defines the text that is shown inthe application menu and the second is a callback function that is calledwhen the item is selected. You can see this more easily by comparingFigure 4.3 with the appuifw.app.menu list.Menus may be hierarchical, that is, a menu item may open a sub-menu.Sub-menus are defined similarly to the main menus as a list of tuples. InExample 12, the second menu item ‘Edit photo’ opens a sub-menu of twoitems, ‘Darken’ and ‘Lighten’. In Figure 4.3, ‘Take Photo’ and ‘Edit Photo’are shown as the main menu and the items ‘Darken’ and ‘Lighten’ as asub-menu corresponding to the ‘Edit photo’ item.The three new functions, photo(), darken() and lighten(), arecallback functions that bind the actions to the menu items.

In this case,each item opens a popup note that relates to the chosen item. As before,you may close the application with the right softkey.Now you should try to build some menus and simple applications byyourself! Building applications is easy, in practice.4.2.2Application BodyThere are several possible objects that can be assigned to the applicationbody:•a canvas that handles graphics on screen (see Chapter 5)•a form which is used to build complex forms that include combinations of various input fields, such as text, numbers and lists (seeChapter 9)•a listbox that shows a list of items (see Chapter 9)• a text object that handles free-form text input (see the PyS60 documentation for more information about this object).You may increase the area that is reserved for the application bodyusing the appuifw.app.screen variable.

Three different sizes areprovided (see Figure 4.4):appuifw.app.screen = "full"appuifw.app.screen = "large"appuifw.app.screen = "normal"4.2.3TabsIn the PyS60 documentation, you can find a description of the appuifw.app.set tabs() function, which, unsurprisingly, is used to define tabsfor the navigation bar. Tabs are defined using a list of strings and callbackfunctions, in a similar way to the application menu.60(a)APPLICATION BUILDING AND SMS INBOX(b)(c)Figure 4.4 Application screen sizes: (a) full, (b) large and (c) normal4.2.4 Content HandlerA special Content handler object, which is part of the appuifw module, is available for opening files of various types, such as images, photosand web pages, using the standard viewer applications of the S60 platform.This object is also used in Chapter 9.4.3 String HandlingThere are only a few applications which do not handle textual dataat all.

In some cases you are not interested in text as such, but youneed to convert textual input to a format which is easy to handleprogrammatically, for instance to lists or integers. Finally, when yourapplication has processed the data, it is often printed out in textual form,so the application must convert internal data structures back to text.Luckily, all this is straightforward in Python. In this section we introducebasic operations on strings, which are used by many examples in thisbook. Section 4.4, which introduces you to the SMS inbox, requires somepower tools for string handling.In Python, strings are objects too.

In effect, this means that allstring-related functions are available automatically without any imports,but you need to remember to use the dot notation, for exampletxt.find("is"), when calling the string functions. Note that it isnot possible to modify a string after creation. All string operations returna new string and leave the original string intact.4.3.1Defining a StringThere are many ways to define new strings:STRING HANDLING61txt = "Episode XXXIV"txt = 'Bart said: "Eat my shorts"'txt = """Homer's face turned red.

He replied: "Why you little!""""The first line uses double quotes to enclose a string. This is the mostusual way to define a string. The second line uses single quotes. It comesin handy if your string contains double quotes. The last line shows the lastresort – if the string contains both single and double quotes and possiblyline breaks, you can enclose the string in three sets of double quotes.4.3.2 Accessing Parts of a StringYou can access individual characters with an index enclosed in squarebrackets, in a similar way to lists.

If you want to find the starting index ofa specific substring, use the function find(). For example, the followingcode outputs first ‘h’ and then ‘i’:txt = "python is great"print txt[3]print txt[txt.find("is")]Above, txt.find("is") returns the value 7 and the character atindex 7 is ‘i’.You can access substrings with the [start:end] notation:txt =printprintprint"python is great"txt[:6]txt[7:9]txt[10:]The print statements output substrings ‘python ’, ‘is ’ and ‘great’.4.3.3Making Decisions with a StringOften you need to make a decision based on a string. You can testwhether a string is non-empty as follows:txt = ""if txt:print "Many characters!"else:print "No characters"This example prints out ‘No characters’.

You can find out the lengthof a string with the function len(). The following example outputs‘password too short’.passwd = "secret"62APPLICATION BUILDING AND SMS INBOXif len(passwd) < 8:print "password too short"If you need to know whether a string contains a specific substring, usethe find() function. It returns −1 if the substring cannot be found.url = "http://www.google.com"if url.find(".com") == -1:print "Access denied!"If the substring should appear at the beginning of the string, use thestartswith() function:if url.startswith("http://"):print "This is a valid URL"4.3.4 Input SanitizationOften you need to normalize the user’s input so that all input is either inlower or upper case. Functions upper() and lower() do the job:a = "PyTHon"print a.upper()print a.lower()The print statements output ‘PYTHON’ and then ‘python’.If you need to be sure that a string does not contain any leadingor trailing white space, use the strip() function.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6451
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее