| << 2 ˌ ȍ˂ | 4 ˌ HTML 챉 >> |
ˌ˼, ˌ ˂ ݵ ˌ˼ , ̹-皂˞ Յ Ꭻ. ? һ ̴ ܱ ˤЫ ̹-皂 ݲ 貮 Ȃ ˅. , һ җ .
˟, ˅. ݵ, , ﹚˂ doc string ܲ Dz ȡ ˞ 貮. , 킯 굎 ۂ ; ס˼ ˌ˂ һ皡 .
, ˼ ꡜ ̴ ȍ ϵ ˅(Windows, UNIX, Mac OS).
"""Framework for getting filetype-specific metadata. Instantiate appropriate class with filename. Returned object acts like a dictionary, with key-value pairs for each piece of metadata. import fileinfo info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3") print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()]) Or use listDirectory function to get info on all files in a directory. for info in fileinfo.listDirectory("/music/ap/", [".mp3"]): ... Framework can be extended by adding classes for particular file types, e.g. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for parsing its files appropriately; see MP3FileInfo for example. """ import os import sys from UserDict import UserDict def stripnulls(data): "strip whitespace and nulls" return data.replace("\00", "").strip() class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)} def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == "TAG": for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == "name" and item: self.__parse(item) FileInfo.__setitem__(self, key, item) def listDirectory(directory, fileExtList): "get list of file info objects for files of particular extensions" fileExtList = [ext.upper() for ext in fileExtList] fileList = [os.path.join(directory, f) for f in os.listdir(directory) \ if os.path.splitext(f)[1].upper() in fileExtList] def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]): "get file info class from filename extension" subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) and getattr(module, subclass) or FileInfo return [getFileInfoClass(f)(f) for f in fileList] if __name__ == "__main__": for info in listDirectory("/music/_singles/", [".mp3"]):print "\n".join(["%s=%s" % (k, v) for k, v in info.items()]) print
| ˂ ̉˼ ˂ 쵌 ݸ ˅. ˂ ˅ ̉ , ˼ ἁ ˂ ȁ MP3 ˅ ἁ ˅ . |
Example 3.2. Output of fileinfo.py
һ˂ ȁ ˼ ̉. ˂ ̉˼ , , ˞ Ҕ ˂ , ˼ ˸ һ˂ ӀӀ ̑ һ .
album=
artist=Ghost in the Machine
title=A Time Long Forgotten (Concept
genre=31
name=/music/_singles/a_time_long_forgotten_con.mp3
year=1999
comment=http://mp3.com/ghostmachine
album=Rave Mix
artist=***DJ MARY-JANE***
title=HELLRAISER****Trance from Hell
genre=31
name=/music/_singles/hellraiser.mp3
year=2000
comment=http://mp3.com/DJMARYJANE
album=Rave Mix
artist=***DJ MARY-JANE***
title=KAIRO****THE BEST GOA
genre=31
name=/music/_singles/kairo.mp3
year=2000
comment=http://mp3.com/DJMARYJANE
album=Journeys
artist=Masters of Balance
title=Long Way Home
genre=31
name=/music/_singles/long_way_home1.mp3
year=2000
comment=http://mp3.com/MastersofBalan
album=
artist=The Cynic Project
title=Sidewinder
genre=18
name=/music/_singles/sidewinder.mp3
year=2000
comment=http://mp3.com/cynicproject
album=Digitosis@128k
artist=VXpanded
title=Spinning
genre=255
name=/music/_singles/spinning.mp3
year=2000
comment=http://mp3.com/artists/95/vxp
˼ վ ݵ . , ˼ ȍ 貮 . վ˼, import module 뵴, ˼ 1 ˌ ˅. վ˼ ˼ ς졒 վ .
Example 3.3. Basic from module import syntax
from UserDict import UserDict
˼ 衒 ˅ 粮 import module ը , һ ˍ嵴: ݵ˂ types˂ ˞ , ס굎˼ ݵ˂ ˂ 櫛, ˞ ȍ .
| ˂ 'from module import'˼ ˂ 'use module' 졒; ˂ 'import module'˼ ˂ 'require module' . | |
Example 3.4. import module vs. from module import
>>> import types >>> types.FunctionType<type 'function'> >>> FunctionType
Traceback (innermost last): File "<interactive input>", line 1, in ? NameError: There is no variable named 'FunctionType' >>> from types import FunctionType
>>> FunctionType
<type 'function'>
| typesݵ˼ 桒, ˂ ̹˂ ˤ 翫. FunctionType˼ ݵ˂ types ˂ 즗. | |
| FunctionType ̹ ˂ ; ס˼ types˂ ը ˍ. | |
| ը˼ FunctionType typesݵ ˞ . | |
| FunctionType types 禂 , ˞ 碱 ˅. |
˼ 'from module import' ȍ ?
סȡ 굎˼, ס˼ ˂ ը, ˼ վ .
ܲ
˼ ̾܂ ̹-皂˞: ˼ ˂ ˂ ˅, ˂ ˼ ˌ ȗ ˅, ˂ ̹Ђ ˅.
˂ ˼ ; ﹚ ˼ , ꮊ ˂ . ˂즗 즗. ˂ ղ class 졒, ˸ ˂ . ˞, ס ݵ, Ҁ һ˂ ȗ ը.
Example 3.5. The simplest Python class
class foo:pass
![]()
| ˂ ˼ foo, ס˼ 굵 ȗ . | |
| һ ˂ , һ ը˞, ˂ Dz , pass ȍ. ˼ ˂ ղ “҃ һ, ” . ס˼ ǡ굵 йը, ﹚һ Ҁ ס˼ ˤ . | |
| ȗ, һ ˂ ݵ ˼ ﹚, if йը, for , ˂ ˂ 坡, ӱ . ӱ ˼ տ ˼ ˅ . |
| pass йը˼ һ C ˂ ({}) . | |
ա, ˞, ˂ ȗ , ˂ ˂ ˂ . һ վ ȓ , ȡ, ˞ 稲 ˼ . һ, C++ ˼ ˂ ˞ ȗ ࡢ皵 . ˂ 炄 翫: __init__ ˅.
Example 3.6. Defining the FileInfo class
from UserDict import UserDict class FileInfo(UserDict):
| , ˂ ȗ˼ 飲 һе. FileInfo UserDict ȗޫ (ס˼ UserDict ݵ ﵂). UserDict ȍ˟ , ȍ˟ Ђ ˅ 煡 ˂ ˤ ̧ ˅ 篫. (UserList UserString ˼ ˅ ˼ ը Ђ ˅.) ˼ ˅, ˌ UserDict . |
| , ˂ ȗ˼ ˂ 飲 һе. ˂ extends ˼ . | |
| ̴ һ ס 皫 , ˼ ȗ . 飲, ˼ չ , ܂, ȗ һЂ ˅. | |
Example 3.7. Initializing the FileInfo class
class FileInfo(UserDict): "store file metadata"def __init__(self, filename=None):
![]()
![]()
| ݵ ﹚ 坡 , doc string ˅ ( 稲 ). | |
| __init__˼ ˂ ̹ 畸 ̉. ˂ ˼ ˞皵 騂.
˞, Ҁ ס˼ (˞, __init__ ˼ ˂ տ ), (ס˼ ț ˂ ̹ տ 禡), 皲 ը. (“init”˼ 騸 -˼ ȍ). 騂, Ҁ ̹ __init__ ̉ 皫 ˅ ը, ˼ ˂ ț ̹ 皡 ˅ ը. һ __init__˼ 煂 ˅ ˌ , ס˼ ˂ ˼ . | |
| __init__ ւ, ݵ ˂ տ 빚 ˂ ˍ ̹ . ˞, 빚 ȗ self ߫. __init__ , self ț ̹ ӫ; Ы, ס˼ ˂ ̹ 皸̂. ˂ ˼ self ˞ ۂ ˅, ̉ ˼ ۂ ; ˼ ס ˤ ˞ ̧ . | |
| __init__ ﹚ 坡 , 빚 ̑ ˅, 빚 ȡ ˂ ˅, ס굎 ̉ ˞ . , filename˼ None , ס˼ ˂ null . |
| ˞, ݵ ˂ տ 빚 (ˍ ̹˂ ˼) self . 빚 C++һ ˅ ղ this˂ , һ self ղ , ߱ . 졒, ס selfȡ ; ˼ 傄 . | |
Example 3.8. Coding the FileInfo class
class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self)self["name"] = filename
![]()
| ˼ ̹-皂-炄 ݲ˼ ȍ “ˌ(extending)” Ҋ 皡 ˅嵴, Ы ȗ˂ ˂ ˟ ˞ ̉. ˼ ; ˼ ȗ ˞ ȗ ˂ ˞ ̉ . | |
| һ ȍ˟ Ȃ, տ 逡 ˅. 빚 filename ̹˂ name˂ . | |
| __init__ ՠ 즗. |
| ˂ ˂ , ˼ ՠ ˞ self, __init__ ւ, ˂ տ 빚 һЂ . ˂ ȗ ˂ ̉ , ˼ ՠ self 빚 ւ . һ ̉, ˼ self 빚 ˤ ǡ굵 ۂ ; ˼ ס ˟ ǂ졒, ˞ ̹ ̧. ˸ 鴦 һ ; ס˼ ݹ˼ , һ ס˼ ݹ 嵴 Ҁ ס˼ (DZ ȍ˂) ˂챉 ը. | |
!. һ ס ի , һ ˼ ס˂ 킯 . ݵ ˂ ˼ ˼ վ , Տ , ˼ ݵ Տ . ݵ 굎 ˯ ՚皦, һ˼ 즗, Ҁ ȡ ˌ졂 סꦤը ˼ ը:
| __init__ ˞, һ һ˂ ˂ , ˼ ȗ˂ __init__ ˞ ̉ . ˼ ՠ˞ : ȗ˂ ˤ ˌ졒 , ˂ ՠ ˞ ˞ ̱ ˞ 빚 皡, ȗ˂ ̉ . | |
ܲ
̹Ђ ˼ ֹ˞. ̹Ђ, ﹚ , __init__ ˂ 빚 ҄煡, ̉ 즗. ՠ˼ ț ̹ .
Example 3.9. Creating a FileInfo instance
>>> import fileinfo >>> f = fileinfo.FileInfo("/music/_singles/kairo.mp3")>>> f.__class__
<class fileinfo.FileInfo at 010EC204> >>> f.__doc__
'base class for file info' >>> f
{'name': '/music/_singles/kairo.mp3'}
| (fileinfo ݵ ˂) FileInfo ˂ ̹ ț ̹ f . ˂ Ҽ, /music/_singles/kairo.mp3 ҄篫, ס˼ "FileInfo'˂ __init__" ˅ filename빚 . | |
| ݵ ̹ ˌ , __class__ 皫嵴, ס˼ ̹˂ . ( ˼ ˂ һ˂ ȁ ̹˂ ա˞ 煹 ւ ; ˂ ˼ .) ˼ Class ւ , ס˼ getName getSuperclass ˼ 皡 ˅, ̹ ̧ȗ ۼ յ. , ˂ ̧ȗ "__class__, __name__, __bases__" ˼ ̹ ˞ ȍ.. | |
| ˼ ̹˂ doc string ﹚ ˼ ݵ 坡 碱 ˅. ˂ ݵ ̹˼ ˼ doc string . | |
| __init__ ˂ filename 빚 self["name"] 쫿 ? , ˅. ̹ ҄ 빚 __init__ Ȳ翫 ( ̹ , self ס ˼ ̧ 篫). |
| , ﹚ ̉ ˂ ț ̹ 즗. C++ ˼ ˞ new Ȑ . | |
ț ̹ , ס굎 ǂ ˼ . ՠ˞, ˞ ̹ , Ҁ ס굎˼ ̹ ՟ˤ ߲ ˞ ϡ ը. ȗ˼ ա..
Example 3.10. Trying to implement a memory leak
>>> def leakmem(): ... f = fileinfo.FileInfo('/music/_singles/kairo.mp3')... >>> for i in range(100): ... leakmem()
| leakmem﹚ ̉ , FileInfo˂ ̹ 졒 ס ﹚˂ , f . ﹚ f ˟ ϡ 桒 ᇂ, ˼ ȗ , һ . ﹚ һ, f ՟ˤ ߲Ы. Ы, ț , FileInfo˂ ̹ 禡 ȗ ˍ ( ס f ȡ ˡ ը), ˼ ̹ ǂ. | |
| leakmem ﹚ ̉ , ס˼ ́ , Ҁ տ, ˼ ț FileInfo leakmem ղ˱ ˟ ǂ ը. |
˂ ձ ˞ “鸹 (reference counting)” . ˼ ݵ ̹ 皂. ˤ˂ Ы, FileInfo ̹ һ˂ ˅ : f. ﹚ ᇂ, f ՟ˤ ߲һ, 鸹 0 Ҳ翫, ˼ ̹ ˞ ǂ.
˟ ՚˟˂ Ы, 鸹 ܂졒, ȹ ȗ ˅. 禂 ˂ ̹ ( , -¡ 뵴, ґ ˟ 翫), ̹ ݵ ˞ ǵ . Ҁ ˼ (騂) ̹ 禡 ȗ ˍ 챉 ը. 2.0 ˞ ˂, “--ȹ(mark-and-sweep)” ձ ˅. ס˼ ˞ ּ 貮ۡ 騂 ȹ ۵ .
˟˂ ̦˂ Ғ, ȡ 낄 ˼ ǵ 煫 ȍ ȍա˼ ȍ翫 嵴, һ ס˼ 騂 첔һ . ՠ˞, ˼ ˯ ՚ ˅ ȹ쵵 뱉 .
ܲ
, FileInfo ȍ˟ . ˤ, UserDict ݵ ˅ UserDict ȓ, ס˼ ˂ FileInfo ˂ ȗ. ˼ ˼ ; ˅, ˂ 坡 .py ˜ˌ ˅. , ס˼ ˂ Ҁ lib ἁ ˜ˌ ˅.
| ˩˂ IDE , ˼ 'File->Locate... (Ctrl-L)' ˂ ˅ ݵ 畸 ˅. | |
, ˼ ը, ȍ˟ ˼ ˌ мЂ . ȗ챉 ˤ, ˌ ˂ ˤ ȫ ˌ : UserString, UserList, UserDict. ȗ ͂ ȍ븇, UserDict ȍ˟ Ҹ, һ ס˼ ݵ ꡜ 坡 һ˂ , ˼ ס Ђ FileInfo ˼ ȍ ̋ ȍ˟-˂ ϡ ˅.
Example 3.11. Defining the UserDict class
class UserDict:def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
![]()
| ˼ UserDict , 굵 ȗ 즗 . | |
| ˼ FileInfo ۲ __init__ . ȗ ˂ 빚 ˼ ͡ 즗. ; 騂 빚 ȗ ̉ , ˂ 빚 眹 ˅. ȗ (dict 빚 һ˂ ȍ˟ ҄븇) 汉 ˂ վ 翫. ס ˂ FileInfo . | |
| ˼ ( Ы “̹ (instance variables)” , C++Ы “՚ (member variables)” ) , ס˼ ˂ ̹ ˂ 皵 . , UserDict˂ ̹ data 翫. ˂ ˅ 禂, ˼ ס һ˂ ﹚ ס˂ ݵ ꡜ ˼ վ, 'instance.data' , ̹ . ˂ 禂챉 ˤ, self ȍ. ˞, ݵ ˼ __init__ ˅ 汉е. , ˼ , Ҁ ˼, ˼ ס굎 ˸ һ˂ է˞ ̉챉 ը. | |
| ˼ ˟ ը (һ ̴ ס ȍ ˞ ). ˼ if йը, һ ˸ ӱ 皫 , ˼ , , ˂ йը ˅ . ˼ ˟ ˞ ը, ˂ йը ס˼ . (ס˼ C++ 飲 ˂ йը ۂ ꡜ .) ˼ ը ȍ ˅, 皫 ӱ ˅, һ ˼ ˼ ȍ . |
| 빚 ˂ ﹚ ۲ӱ , , Ȃ һ˂ ҹ˂ 빚, ˼ ˂ 빚 ˼ ˂ ˅. ݲЫ (PL/SQL ˜) 皲 빚 ˂ ﹚ ۲ӱ ; , Ȃ һ˂ 빚 , ˼ ҹ˂ ˼ ˂ 빚 皡 ˼ 皫 ˂ ˅ ˼ ݵ ; ס˼ ﹚ ۲ӱ ˼ ˂ 嵵 . ˂ 빚 ȗ, __init__ __init__ __init__ . ˂ __init__ ˅ ˅, __init__ 翫, ס 빚 ˂ 皦, ס˼ ȗ ȗ˂ __init__ ۲ . | |
| __init__ ˅, ̹˂ ݵ 汉 ȗ 즗. ס ˼ ՚ ̡ ಈ ˅ . | |
Example 3.12. UserDict normal methods
def clear(self): self.data.clear()def copy(self):
if self.__class__ is UserDict:
return UserDict(self.data) import copy
return copy.copy(self) def keys(self): return self.data.keys()
def items(self): return self.data.items() def values(self): return self.data.values()
| clear ȗ˞ ; ס˼ ˦һ һ 稹 ˞ ȍ. ݵ , clear ˂ տ 빚 self 翫. (즗, ˼ ̉ self ւ ; ס˼ 煫 .) ˌ ˂ ˞ ׁ 즗: ȍ˟(data) ˜ˌ졒, ȍ˟ ݵ ˂, ȍ˟ ȗ˂ վ˟ ́ӫ. ( ˯ ՚ , ȍ˟˂ clear ˂ ݵ ¡ ȏς.) | |
| ȍ˟˂ copy ț ȍ˟ ՠ ס˼ ˂ ȍ˟ (- ݵ) ˼ ȍ. һ | |
| __class__ ȍ self UserDict 낄; , ˞秂 , Ҁ UserDict ȍ վ 豉 ը: ț UserDict ס self.data и ݲ ȍ˟ 煲. | |
| self.__class__ UserDict 즗, self Ӳ UserDict˂ ( FileInfo坡), Ӏ . UserDict ˂ ˂ һ ȍ վ ; , ˅皵 , ס굎 騸 ݵ ȍ ˅ . ﵵ, ݵ һ , ס˼ copy . һ ȍ 皫 ( ס ס˼ ֡ ȍ ݵ). copy ˂˞ ̹ ȍ ˅ ̾܂ Ȃ ˅, ס ȍ졒 ˅ վ. | |
| һ ˼ ֹ˞, ̉ self.data ˅ ˌ վ ˟. |
ܲ
, ˂ ˅ ˼ ˅. ( ȗ˞ ) ˞ ̉ , ȗ ˼ ը ȍ ˂ ̉.
˟˂ , ȗ һ˂ ȍ˟ 뱉 ˤ . һ ȗ ̾܂ , Ҁ ̉ ȍ˟ ˅ ձ ը. , ˼ ˞ Ȃ ւ ը յ ˅ ۂ ˅. ̉ : ס굎˼ --̉ ը ̉ ߱ һ˂ վ ϡ.
Example 3.13. The __getitem__ special method
def __getitem__(self, key): return self.data[key]
>>> f = fileinfo.FileInfo("/music/_singles/kairo.mp3") >>> f {'name':'/music/_singles/kairo.mp3'} >>> f.__getitem__("name")'/music/_singles/kairo.mp3' >>> f["name"]
'/music/_singles/kairo.mp3'
| __getitem__ . ȗ clear, keys, values, ס˼ ȍ˟ վ˟ ˂ ՠ. һ ȡ ס˼ ̉ 皫? ˸, ˼ __getitem__ ˞ ̉ ˅, һ ȍȗ ˼ 皫 ; һ ס ȡ 煱 ˤ ס 졒 ˅. __getitem__ 騂 ȍ ˼ ס ̉ . | |
| ˼ ȍ˟ յ챉 ˤ ȍ ը , ס˼ ȗ ՠ. һ ˅: ӱ в, ˼ ը ̉ 'f.__getitem__("name")' . ס __getitem__ ; ס ̉ ˅ 즗, ˼ 騂 ը ȍ ס ̉ ˅ ˅. |
Example 3.14. The __setitem__ special method
def __setitem__(self, key, item): self.data[key] = item
>>> f {'name':'/music/_singles/kairo.mp3'} >>> f.__setitem__("genre", 31)>>> f {'name':'/music/_singles/kairo.mp3', 'genre':31} >>> f["genre"] = 32
>>> f {'name':'/music/_singles/kairo.mp3', 'genre':32}
| __getitem__ , __setitem__˼ ȍ˟, self.data վ˟ ˂ . __getitem__, ˼ ᱸ ס ˞ ̉皫 ; ˼ 騂 ը ȍ __setitem__ ̉. | |
| f ȍ˟ 硒 и ґ ˂ , __setitem__˼ ˤˌ˂ ա , ˼ ՟ ȍ˟ ը . ˼ ӱ в f.__setitem__("genre", 32) ̉. |
__setitem__˼ ̉ ը , һ ס˼ ˟ . UserDict __setitem__ ˂ , ס ˂ ˍ˂ ȗ ۲ ˅. ȍ˟ ˂ ˅һ ˌ ȍ˟ ҄Ы ˂ ˤ ˂ ˅.
Ҋ˼ ˌ 졒 ˅ ˟̹ ˂ ȁ. ˼ ˂ ށ յ 衒 ˅ 翫. (˂ ˤ ˼) , ˞ ́ վ . ˼ __setitem__ ۲ӡ, , է ˞ ̧븇 .
, MP3FileInfo FileInfo˂ . MP3FileInfo˂ (name) ۵ , ס˼ ( ȗ FileInfo ) name ۂ ; ס˼ MP3 ˤ ̹ ȫ ˟̹ Ҹ.
Example 3.15. Overriding __setitem__ in MP3FileInfo
def __setitem__(self, key, item):if key == "name" and item:
self.__parse(item)
FileInfo.__setitem__(self, key, item)
| ˼ ˂ __setitem__ 騂 ȗ ˼ վ ˂ . ˼ , Ҁ ˼ ̉ ը, ˼ ס ۡҹ˂ 빚 ˂ ȗ. (˞ , ҹ, 빚˂ ˼ ըϡ .) | |
| ˟̹ MP3FileInfo ˂ ˅: һ˂ name 졒 һ, ˂ 챉 . | |
| name ˤ ˂ ˼ __parse Ђ . ˼ MP3FileInfo ˂ , ס ̉ , ס self . __parse ̉ ˂ ȗ˞ ﹚ ̣ 뵴, ס˼ ; self.__parse ̉ ˂ ̣ . ˼ ț ; ˼ ˼ վ 禂. | |
| ˂ , ȗ˂ ̉챉 . 즗, ˼ ፲ ; ˼ ס ˅. ˼ ˞ ȗ, ס __setitem__ 皡 ˅ 皦, FileInfo ̉졒 ˅ . ס˼ 圫, Ҁ ˼ ȗ˂ ̦ ̉졒 ˅ ̣ , ˼ UserDict ˂ __setitem__ ̣ ̉ ը. |
| 碱 , ˼ ˂ ˅: self.attribute. ̉ , ˼ ˅: self.method. | |
Example 3.16. Setting an MP3FileInfo's name
>>> import fileinfo >>> mp3file = fileinfo.MP3FileInfo()>>> mp3file {'name':None} >>> mp3file["name"] = "/music/_singles/kairo.mp3"
>>> mp3file {'album': 'Rave Mix', 'artist': '***DJ MARY-JANE***', 'genre': 31, 'title': 'KAIRO****THE BEST GOA', 'name': '/music/_singles/kairo.mp3', 'year': '2000', 'comment': 'http://mp3.com/DJMARYJANE'} >>> mp3file["name"] = "/music/_singles/sidewinder.mp3"
>>> mp3file {'album': '', 'artist': 'The Cynic Project', 'genre': 18, 'title': 'Sidewinder', 'name': '/music/_singles/sidewinder.mp3', 'year': '2000', 'comment': 'http://mp3.com/cynicproject'}
| ˜, 桒, MP3FileInfo˂ ̹ . ( ǂ ˅嵴 Ҁ __init__ ˂ filename 빚 ˞ ը.) MP3FileInfo ˂ __init__ Ղ, ˼ ȗ˂ ̦ FileInfo˂ __init__ ̣. __init__ UserDict˂ __init__ ̉ һ name filename ۂ, ס˼ None뵴, Ҁ ҄ ը. , mp3file ˸ һ˂ , name ȍ˟ , ˼ None. | |
| ˍ . mp3file˂ name ۂ (UserDict 즗) MP3FileInfo ˅ __setitem__ է́ӫ, ס˼ name ۂ 貮ۡ self.__parse ̉. __parse ̧˞ ˸ 졒, ˼ ̉ ס ˂ ۂ ˅: album, artist, genre, title, year, comment. | |
| name ˼ Չ : ˼ __setitem__ ̉, ס˼ self.__parse ̉, ס˼ ݵ ۂ. |
__getitem__ __setitem__ ȡ ˼ ˅. ˼ ˼ ȵ 篫.
Example 3.17. More special methods in UserDict
def __repr__(self): return repr(self.data)def __cmp__(self, dict):
if isinstance(dict, UserDict): return cmp(self.data, dict.data) else: return cmp(self.data, dict) def __len__(self): return len(self.data)
def __delitem__(self, key): del self.data[key]
| __repr__ repr(instance) ̉ ̉ . repr ﹚ ̹˂ ը ՠ ˌ ﹚. ס˼ ̹ 즗, ݵ ̹ . ס 衒 ˅ 졒 ˼ repr ւ. ȗ飫˞ ˩, 졒 ENTER , ˼ repr ȍ ˂ ̉傄. ˂ ȍ˟ d print repr(d) 貮. | |
| ̹ ҂ __cmp__ ̉. ՠ˞, ˼ ̹ 즗, ˂ ̹, == ҂ ˅. ˌ 煵 ˂ ˅; , ȍ˟˼ ݵ ˼ , ը˼ ˼ ˼ ˂ ը . ̹ , ˼ __cmp__ ˂ ˅ Ғ ˅, һ ˼ == ȍ ˂ ˂ ̹ ҂ ˅ ˼ ˂ __cmp__ ̉ . | |
| __len__ len(instance) ̉ ̉. len ﹚ ̹˂ ՠ ˌ ﹚. ס˼ 皡 ˅ ̾ 煵 ̹ . ը˂ len˼ ˂ ը˂ ҹ 翫; ȍ˟˂ len˼ ˂ ˂ ҹ 翫; ˼ ˂ len˼ ˂ ˂ ҹ 翫. ̹, __len__ ˂졒 Ȑ , һ len(instance) ̉즗 ˼ ˂ __len__ ̉ . | |
| __delitem__˼ del instance[key] ̉ ̉, ˼ ס ȍ˟ Ҽ˞ ϡ վ . del ̹ ȍ , ˼ __delitem__ ̉. |
| , ˼ ˂ ը ˼ ա˞ ˤ 禂 str1 == str2ȍ ۂ. ̹ (object identity) , ס˼ 'str1 is str2' 翫. ը ҂, ˼ str1.equals(str2) ȍ ; , ˼ str1 == str2 ȍ . ˂ '==' ˂ 챉 ը ˂ ȗ ˼ 쵵 Տ ˼ “ (gotchas)” ̡˞ 皵 . | |
, ˼ ࡢ졒 ˅皵 , “һ˂ Dzݡ ݵ 쵎 һ ˌ ˅.” ȍ˟ ˼ ˌ ȗ ˅ Ȕ ˅ ˼ ȍ ( ˟̹ UserDict ) . һ ˅ , ˟ , Ҁ ס굎˼ UserDict ˼ ˌ 즗, ȍ ˅ ը.
ȍ˟ ˼ - , __setitem__ ˂븇, ˜ˌ ˅ ˂킄. __getitem__ ˂븇 ¹ ˅. __cmp__ ˂ ݵ == ҵ ˅. ˂ һҸ, GetLength ˂ ; __len__ ˂졒 len(instance) ȍ즗.
| ̹-皂 ݲ ̹˂ ա˞ ݵ ˂쵵 煫 ՠ (“ ̹ GetLength 翫 ”), __len__ ˼ ˂ ̹˂ Ғ˞ ݵ ˂쵵 篫 (“ ̹ 翫”). | |
˼ ˅. 쵵 煫 ˂ ݵ 篼 ˅, ̹ ˼ 졒, ȩ ݵ ˅. (˂ ՟˞ ի , չ һȫ .) __call__ ﹚ 쵵 煲, ˼ ̹ ˞ ̉ ˅. ˅ ܱ-˟ ӱ-˟ 皵 篫; ס굎 ˂ ˌ Ғ˂ .
ܲ
˼ 衒 ˅, ס˼ ˂ ̹ . ˼ , ס˼ ̹ 졒 ˅ .
Example 3.18. Introducing class attributes
class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)}
>>> import fileinfo >>> fileinfo.MP3FileInfo<class fileinfo.MP3FileInfo at 01257FDC> >>> fileinfo.MP3FileInfo.tagDataMap
{'title': (3, 33, <function stripnulls at 0260C8D4>), 'genre': (127, 128, <built-in function ord>), 'artist': (33, 63, <function stripnulls at 0260C8D4>), 'year': (93, 97, <function stripnulls at 0260C8D4>), 'comment': (97, 126, <function stripnulls at 0260C8D4>), 'album': (63, 93, <function stripnulls at 0260C8D4>)} >>> m = fileinfo.MP3FileInfo()
>>> m.tagDataMap {'title': (3, 33, <function stripnulls at 0260C8D4>), 'genre': (127, 128, <built-in function ord>), 'artist': (33, 63, <function stripnulls at 0260C8D4>), 'year': (93, 97, <function stripnulls at 0260C8D4>), 'comment': (97, 126, <function stripnulls at 0260C8D4>), 'album': (63, 93, <function stripnulls at 0260C8D4>)}
| MP3FileInfo ˂ ̹ 즗, ̹. | |
| tagDataMap˼ : ը˞ , ˂ . ˂ ̹ 챉˟ ס˼ ȍ. | |
| ˼ ˂ ݵ ̹ ݵ ȍ. |
| , (Ы ) ˞ (Ы ) ̹ ˼ ݵ ˂ (һ static, һ ) ˂. Ы, ˂ ˅; ˼ __init__ ˂. | |
˼ -˂ ȗ ȍ (ס˼ MP3FileInfo ȍ վ), һ ס굎˼ ȗ .[4] ˼ ס굎 ˅.
Example 3.19. Modifying class attributes
>>> class counter: ... count = 0... def __init__(self) ... self.__class__.count += 1
... >>> counter <class __main__.counter at 010EAECC> >>> counter.count
0 >>> c = counter() >>> c.count
1 >>> counter.count 1 >>> d = counter()
>>> d.count 2 >>> c.count 2 >>> counter.count 2
| count counter ˂ . | |
| __class__ (ݵ ˂) ݵ ̹ ˌ . ס˼ self ˂ ̹ ( , counter ). | |
| count Ղ, ˂ ̹ 챉 ˟, ס˼ . | |
| ˂ ̹һ __init__ ̉嵴, ס˼ , count 1 盡́ӫ. ˼ ț ̹ 즗, 퀣. | |
| տ ̹ һ , count 盡́ . ȡ ˂ ݵ ̹ 즗. |
˂ ݲ, ˼ ˸˂ Ҋ 翫; ȍ˞ ﹚, ס˼ ˂ ݵ ̉ ; ȍ˞ , ס˼ ˂ ̉ ; ȍ˞ , ס˼ ˂ 碱 . ˂ ݲ , ˂ ﹚, , ˼ ȍ˞ ˼ ˞ ˼ ˟˞ ˂ ˂ ۵.
MP3FileInfo, ˂ ˅: __parse __setitem__. Ғ˂ , __setitem__˼ ; , ˼ ̹ ȍ˟ ը ȍ ס ˞ ̉ . һ ס˼ ˞, ˼ ̾܂ ˅ (皲 fileinfoݵ е) ס ˞ ̉ ˅ . , __parse ȍ˞, Ҁ ס˼ ˂ ˂ կը 皱 ը.
| ˂ ﹚, , ˼ ˂ ˂ կը (һ ˂ կ ը һ ), ס˼ ȍ˞; ݵ ˼ ˞. | |
| , (__setitem__ ˼) ݵ (__doc__ ˼) ˌ ˼ ˞ ߱ : ˼ ݵ ˂ կը 졒 Ы. ˂ ᱸ ; ס˼ ( ȍֵ) 鴦́ . | |
| ( ˂ 碱) Ҋ ˟ . ( ˂ 碱) ȍ˞һ ˼ (һ 碱) ˞. | |
Example 3.20. Trying to call a private method
>>> import fileinfo >>> m = fileinfo.MP3FileInfo() >>> m.__parse("/music/_singles/kairo.mp3")Traceback (innermost last): File "<interactive input>", line 1, in ? AttributeError: 'MP3FileInfo' instance has no attribute '__parse'
| ȍ˞ ̉졒 , ˼ ˍ , ˼ ˧ է́ӫ. ա ס˼ ˍ , һ ס˼ ȍ˞, Ы 碱 .[5] |
ܲ
˼ ̹-皂 ݲ, try...except ˅.
| ˼ try...except ȍ raise ȍ է́ӫ. C++ ˼ try...catch ȍ Ꭻ, throw ȍ է́ӫ. | |
ݵ , ˼ ˅. 皡 ˅ ˼ ˜Ђ ݲ Յ嵴 ւ , ˼ ȍ 桒 ݲ ȍ , ˼ .
һ ˅; ˞ ˅ ݵ ݵ˼ ס ȍ, ̹ ˼ ס굎 է́ . ˼ ס굎 ՠ˞ ̴ .
, IDEЫ ˜ ˍ˅ Ҕ : 첔Ы, ̉ (˂ IDE , ȼ˞ ˂˞ Ț 챉 ), ס . ˼ ˼ (unhandled) ; է , ס ˞ 皂졒 , ˌ ˤ ҄̀ ղ, ˼ ˂ ՚ ۼ Ֆȡ ֱ. IDE, ס˼ , һ ˂ ȗ է, ˟̹ ˼ ϵ һ .[6]
, ˟ ̾ Ы . , էൂ, (handled) ˅. ˂ (ˍ 碱 ꡜ ˼) ՚ס ˅ ը , һ ˼ , ס ˅ . һ С , ס ˍ 皵 ; ¡졒 , ס ˅һ, ˼ ס 碱챉 ˤ 騂 皡 ˅ ˅. ˂ 皵 , ˼ try...except ȍ .
Example 3.21. Opening a non-existent file
>>> fsock = open("/notthere", "r")Traceback (innermost last): File "<interactive input>", line 1, in ? IOError: [Errno 2] No such file or directory: '/notthere' >>> try: ... fsock = open("/notthere")
... except IOError:
... print "The file does not exist, exiting gracefully" ... print "This line will always print"
The file does not exist, exiting gracefully This line will always print
皫 (, һւ , ˂ ˟̹ ˼ ̾Ղ ) һ 炯. ˼ -ˍ ȍ ̹ ȫ ? ˼ ᵍ ȡ е ˂ 肯 , ˯, ˂ ˼ 킄 ˤ ˼ ̧˞ . һ ᱡ 騸; ס˼ ˍ˂ ըϡ . , ˞ 첔Ы, ˼ ը ˞ վ ס굎 ˅.
˞ 禡 ˤ ȍൎ ˅. ˞ ˂ ՠ˞ ȍ˼ ݵ 硒 ̵ , ס һ 貮 . ˍ ݵ ImportError է́ . ˼ - ݵ ȍ 悄 ˂ ˂ ˅, ˼ ˅ (Ы -˂˞ ˂ ݵ ܂ ).
Example 3.22. Supporting platform-specific functionality
, ȍ յ챉 ˤ ˌ ݵ, getpass ݵ . յ ˼ ܸ, ˩, OS , һ ݵ .
# Bind the name getpass to the appropriate function try: import termios, TERMIOSexcept ImportError: try: import msvcrt
except ImportError: try: from EasyDialogs import AskPassword
except ImportError: getpass = default_getpass
else:
getpass = AskPassword else: getpass = win_getpass else: getpass = unix_getpass
ܲ
˼ ݸ б ˤ, ˌ ﹚ open 翫. open ˼ ̹ ՠ嵴, ס˼ ۼ յ졒 챉 ˤ 翫.
>>> f = open("/music/_singles/kairo.mp3", "rb")>>> f
<open file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988> >>> f.mode
'rb' >>> f.name
'/music/_singles/kairo.mp3'
| open 幹 ˂ Ҽ ̑ ˅: , ݵ, ՚ Ҽ. տ˂ , 湚˞; ҫ ˞. ۵ , ˼ ݵ ܱ ˤ . ݵ ܱ ˤ С ˅. (print open.__doc__ ݵ ݵ ˅.) | |
| open ﹚ ̹ ՠ (皱皫, ˼ 皫 ). ̹ ˂ 翫. | |
| ˂ mode ˼ ݵ ˅. | |
| ˂ name ˼ ̹ վ ˂ ˅. |
>>> f <open file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988> >>> f.tell()0 >>> f.seek(-128, 2)
>>> f.tell()
7542909 >>> tagData = f.read(128)
>>> tagData 'TAGKAIRO****THE BEST GOA ***DJ MARY-JANE*** Rave Mix 2000http://mp3.com/DJMARYJANE \037' >>> f.tell()
7543037
>>> f <open file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988> >>> f.closed0 >>> f.close()
>>> f <closed file '/music/_singles/kairo.mp3', mode 'rb' at 010E3988> >>> f.closed 1 >>> f.seek(0)
Traceback (innermost last): File "<interactive input>", line 1, in ? ValueError: I/O operation on closed file >>> f.tell() Traceback (innermost last): File "<interactive input>", line 1, in ? ValueError: I/O operation on closed file >>> f.read() Traceback (innermost last): File "<interactive input>", line 1, in ? ValueError: I/O operation on closed file >>> f.close()
| ̹˂ closed ˼ ̹ վ́ ˅ ӫ. , ˼ ˟ ˅ (closed 0). ˼ ̸ ݂, ˂ ݵ , ᴵ ס굎 碱 ˅. ̅ . | |
| ˤЫ, ̹˂ close ̉즗. ˼ ( ˅) 皂졒 ˅ ˇˌ ς 煡, ( ˅) ̸ 桒 ՚ 굎 ˜ˌ 篫, ̸ 篫. closed ˼ ˅ 篫. | |
| ̹ ˍ챉 ̇ 皫 . f ՟ˤ ߲ ˼ ȏϵ ˍ . , 皱 굵 ̉ ; ݵ է́ӫ. | |
| ̹ close ̉ է́ ; ס˼ ܂. |
Example 3.26. File objects in MP3FileInfo
try:fsock = open(filename, "rb", 0)
try: fsock.seek(-128, 2)
tagdata = fsock.read(128)
finally:
fsock.close() . . . except IOError:
pass
| վ졒 ܫ ˼ ˤ챉 ը է́ ˅, ݵ try...except ˌ. (, ˞ ӱ, ˫챔? ˼ ס ȍ챉 .) | |
| open ﹚ IOError է́ ˅. ( ˍ ˅.) | |
| seek IOError է́ ˅. ( 128 ˅.) | |
| read IOError է́ ˅. ( ݸ Տ 皡 ˅, ˼ ס ˅ ˅.) | |
| ˼ ț: try...finally . open ﹚ ˂ ˞ , seek ˼ read ˂ է 皦, 騸 ס 챉 . ס try...finally ȍ : try է́ӫ 皦, finally ˂ ȗ . Ǹ 첔Ы 皦, ס˼ “” ࡢ즗. | |
| , IOError . ˼ open, seek, ˼ read ̉ է IOError ˅ . , , Ҁ 硒 ݵ ˼ ס Ǹ̂졒 翂 ը. (즗, pass ˂ йը ǡ굵 .) ס˼ ˟ ˞; “ ”˼ ˞ ǡ굵 ˅. ס˼ ˟ 煵, try...except ˂ ˸ ȗ˞ 翂 . |
Further reading
˂ ݲ, for ˅. 皱 ס굎 삄 ˼ 쵎 ˼ ס굎 汉 ը.
˂ ݲ ˼ 傄 , ˼ ˼ . ˸, , ۂ ۹˂ ՟ˤ ˂졁һ ˼ ՠ˞ ̹ ˂. һ Ы, for ՠՂ , ˼ վ տ .
Example 3.27. Introducing the for loop
>>> li = ['a', 'b', 'e'] >>> for s in li:... print s
a b e >>> print "\n".join(li)
a b e
| for ˤ ը˼ տ . li , s, տ , ˂ 櫑 ̑ . | |
| if йը ˼ ݵ ӱ , for ҹ˂ 뵵 ˅. | |
| 皱 for : ֱ皫 ס . join ˼ տ ݲЫ һ ˼ for ȍ Ҕ. |
Example 3.28. Iterating through a dictionary
>>> for k, v in os.environ.items():![]()
... print "%s=%s" % (k, v) USERPROFILE=C:\Documents and Settings\mpilgrim OS=Windows_NT COMPUTERNAME=MPILGRIM USERNAME=mpilgrim [...snip...] >>> print "\n".join(["%s=%s" % (k, v) for k, v in os.environ.items()])
USERPROFILE=C:\Documents and Settings\mpilgrim OS=Windows_NT COMPUTERNAME=MPILGRIM USERNAME=mpilgrim [...snip...]
| os.environ ˂ ̸ ˂ ˅ ȍ˟. ˩, ˼ 碱 ˅ ̸ ȍ . ܸ, ס굎˼ ˂ ˂ Ү Ȳ . OS, Ҋ , ȍ˟˼ ˅. | |
| os.environ.items()˼ ˂ : [(key1, value1), (key2, value2), ...] ՠ. for ՠՂ. տ ˟, ס˼ key1 k 졒 value1 v , k = USERPROFILE v = C:\Documents and Settings\mpilgrim. տˍ ˟, k տ , OS յ졒, v ȗ˂ , Windows_NT յ. | |
| - տ, ˼ ˟̹ for ˂ йը ˅. ˂ ˞ ˂ ը; һ ס 粮 Ҁ ס˼ 졒 ˅ ȍ˟ ߡ, һ ˂ ը ͂ 騂 煱 ը. ˼ for 챉 粮. ˼ һ ̉ , ՚˟ , Ҁ ˼ йը ˂ print йը ˅ ը. |
Example 3.29. for loop in MP3FileInfo
tagDataMap = {"title" : ( 3, 33, stripnulls),
"artist" : ( 33, 63, stripnulls),
"album" : ( 63, 93, stripnulls),
"year" : ( 93, 97, stripnulls),
"comment" : ( 97, 126, stripnulls),
"genre" : (127, 128, ord)}
.
.
.
if tagdata[:3] == "TAG":
for tag, (start, end, parseFunc) in self.tagDataMap.items():
self[tag] = parseFunc(tagdata[start:end]) 
| tagDataMap˼ MP3 ̣ ˅ ˂. ˼ - 浌 ˜ˌ ˅; ˂ 128 , ˂ 3 32 ȗ ґ , 33-62 ˼ ȗ , 63-92 ˼ ՟ , . ˼ tagDataMap˼ ፲ ȍ˟, ˼ ˂ ۹ ﹚ ւ졒 ˅ . | |
| ˼ ˉ , һ . for ˂ 禫 items ՠ ւ ˂ . 즗, items ˼ (key, value)˂ ˂ ՠ. ˂ տ ("title", (3, 33, <function stripnulls>)), տ , tag "title", start 3, end 33, parseFunc stripnulls﹚ յ. | |
| ˂ MP3 ˤ ݵ Ҽ ̧̉Ղ, ˜ˌ ˼ . tagdata start end 僡Ҳ ˤ ˂ յ졒, parseFunc ̉ -, ˂ȍ-ȍ˟ self ˅ tag˂ . tagDataMap ˅ ݵ ՠՂ , self ݵ ˤ 翫, ˼ ס ȡ 킯. |
ݵ ꡜ 坡, ݵ˼ ̹. ﵂, ˼ ˟ ȍ˟ sys.modules ݵ յ ˅.
Example 3.30. Introducing sys.modules
>>> import sys>>> print '\n'.join(sys.modules.keys())
win32api os.path os exceptions __main__ ntpath nt sys __builtin__ site signal UserDict stat
| sys ݵ˼ 졒 ˅ ˂ ՚˟ |