Wikipedysta:Warszk/Python
Z Wikibooks, biblioteki wolnych podręczników.
Spis treści |
[edytuj] Użycie type, str, dir i innych wbudowanych funkcji
Python posiada mały zestaw bardzo użytecznych funkcji wbudowanych. Wszystkie inne funkcje znajdują się w poszczególnych modułach. Podobnie wygląda w przypadku innych języków skryptowych (jak Visual Basica)
[edytuj] Funkcja type
Funkcja type zwraca typ danych kazdego obiektu. Możliwe typy znajdują się w module types. To jest pomocne w przypadku funkci pomocy, która może obejmować różne typy danych.
Przykład 4.5. Przedstawienie type
>>> type(1) #1 <type 'int'> >>> li = [] >>> type(li) #2 <type 'list'> >>> import odbchelper >>> type(odbchelper) #3 <type 'module'> >>> import types #4 >>> type(odbchelper) == types.ModuleType True
- Argumentem type może być cokolwiek, stałe, łańcuchy znaków, listy, słowniki, krotki, funkcje, klasy, moduły a także typy.
- type może pobrać zmienną i zwrócić jej typ.
- type współpracuje również z modułami.
- Możesz porównywać typy obiektów.
[edytuj] Funkcja str
Funcka str przekształca dane w łańcuch znaków. Każdy typ danych może być przekształcony w taki łańcuch.
Przykłade 4.6. Przedstawienie str
>>> str(1) #1
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> horsemen
['war', 'pestilence', 'famine']
>>> horsemen.append('Powerbuilder')
>>> str(horsemen) #2
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper) #3
"<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>"
>>> str(None) #4
'None'
- Dla prostych typów danych, jak liczby całkowite, można się spodziewać poprawnej konwersji, bo taką zapewniają wszystkie popularne języki programowania.
- Jednakże, str pracuje z każdym obiektem jakiegokolwiek typu. tutaj przykład listy.
- str współpracuje również z modułami. Zauważ, że łańcuch reprezentujący moduł zawiera ścieżkę do modułu znajdującego się na dysku, tak więc twój wynik może być inny.
- Możemy nawet przekonwertować None na napis. Niedługo wykorzystamy taką możliwość.
[edytuj] Funkcja dir
At the heart of the info function is the powerful dir function. dir returns a list of the attributes and methods of any object: modules, functions, strings, lists, dictionaries... pretty much anything.
Przykład 4.7. Przedstawienie dir
>>> li = []
>>> dir(li) #1
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d) #2
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
>>> import odbchelper
>>> dir(odbchelper) #3
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']
- li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.
- d is a dictionary, so dir(d) returns a list of the names of dictionary methods. At least one of these, keys, should look familiar.
- This is where it really gets interesting. odbchelper is a module, so dir(odbchelper) returns a list of all kinds of stuff defined in the module, including built-in attributes, like __name__, __doc__, and whatever other attributes and methods you define. In this case, odbchelper has only one user-defined method, the buildConnectionString function described in Chapter 2.
Finally, the callable function takes any object and returns True if the object can be called, or False otherwise. Callable objects include functions, class methods, even classes themselves. (More on classes in the next chapter.)
Example 4.8. Introducing callable
>>> import string
>>> string.punctuation #1
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.join #2
<function join at 00C55A7C>
>>> callable(string.punctuation) #3
False
>>> callable(string.join) #4
True
>>> print string.join.__doc__ #5
join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
- The functions in the string module are deprecated (although many people still use the join function), but the module contains a lot of useful constants like this string.punctuation, which contains all the standard punctuation characters.
- string.join is a function that joins a list of strings.
- string.punctuation is not callable; it is a string. (A string does have callable methods, but the string itself is not callable.)
- string.join is callable; it's a function that takes two arguments.
- Any callable object may have a doc string. By using the callable function on each of an object's attributes, you can determine which attributes you care about (methods, functions, classes) and which you want to ignore (constants and so on) without knowing anything about the object ahead of time.
[edytuj] Wbudowane funkcje
type, str, dir, and all the rest of Python's built-in functions are grouped into a special module called __builtin__. (That's two underscores before and after.) If it helps, you can think of Python automatically executing from __builtin__ import * on startup, which imports all the “built-in” functions into the namespace so you can use them directly.
The advantage of thinking like this is that you can access all the built-in functions and attributes as a group by getting information about the __builtin__ module. And guess what, Python has a function called info. Try it yourself and skim through the list now. We'll dive into some of the more important functions later. (Some of the built-in error classes, like AttributeError, should already look familiar.)
Przykład 4.9. Wbudowane atrybuty i funkcje
>>> from apihelper import info >>> import __builtin__ >>> info(__builtin__, 20) ArithmeticError Base class for arithmetic errors. AssertionError Assertion failed. AttributeError Attribute not found. EOFError Read beyond end of file. EnvironmentError Base class for I/O related errors. Exception Common base class for all exceptions. FloatingPointError Floating point operation failed. IOError I/O operation failed.
[...snip...]