Python论坛  - 讨论区

标题:[python-chinese] DiveIntoPython例程不解!

2007年02月01日 星期四 09:08

zhbguan zhbguan在lemote.com
星期四 二月 1 09:08:53 HKT 2007

DiveIntoPython5.4ÖУ¬ÆäÖÐÒ»¸öÀý³ÌΪfileinfo.py£º

"""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   ###´Ë´¦MP3FileInfoµÄÒ»¸öʵÀýµ÷ÓÃÁ˸¸ÀàFileInfoµÄ__int__º¯Êý£¬
                                  ###µ«ÊÇ£¬self["name"] = filenameÔõô»áµ÷ÓÃMP3FileInfoÀàµÄ__setitem__º¯ÊýÄØ£¿£¿
                                  ###´Ë´¦ÎÒÖªµÀ£¬__setitem__ÊÇרÓú¯Êý£¬Ò²¾ÍÊÇ˵£¬Èç¹û³öÏÖ¸³ÖµµÄÇé¿ö£¬ÏµÍ³»á×Ô¶¯µ÷ÓÃÕâ¸öº¯ÊýµÄ¡£
                                  ###ÎÒµÄÎÊÌâÊÇ£º¾ÍÊǵ÷ÓõĻ°£¬Ò²Ó¦¸Ãµ÷ÓÃFileInfoµÄ__setitem__º¯Êý°É£¿£¿´Ë´¦selfÊÇÖ¸ÄǸöʵÀý¶ÔÏó°¡£¿
                                  ###ÊÇÖ¸MP3FileInfoµÄʵÀý¶ÔÏóô£¿£¿£¿
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"
    fileList = [os.path.normcase(f)
                for f in os.listdir(directory)]           
    fileList = [os.path.join(directory, f) 
               for f in fileList
                if os.path.splitext(f)[1] 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
ÎÊÌâ¼ûÉÏÊö×¢ÊÍ£¡£¡£¡

¶àл£¡£¡¶àл£¡£¡£¡




zhbguan
2007-01-30
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/aac5c8d9/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 09:36

Linker Lin linkerlin88在gmail.com
星期四 二月 1 09:36:09 HKT 2007

Python会先在本类对象的函数表中查找,
找不到会顺着继承树向北查找。


On 2/1/07, zhbguan <zhbguan在lemote.com> wrote:
>
>  DiveIntoPython5.4中,其中一个例程为fileinfo.py:
>
>
> """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   ###此处MP3FileInfo的一个实例调用了父类FileInfo的__int__函数,
>
>                                   ###但是,self["name"] = filename怎么会调用MP3FileInfo类的__setitem__函数呢??
>
>                                   ###此处我知道,__setitem__是专用函数,也就是说,如果出现赋值的情况,系统会自动调用这个函数的。
>
>                                   ###我的问题是:就是调用的话,也应该调用FileInfo的__setitem__函数吧??此处self是指那个实例对象啊?
>
>                                   ###是指MP3FileInfo的实例对象么???
>
> 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"
>     fileList = [os.path.normcase(f)
>                 for f in os.listdir(directory)]
>     fileList = [os.path.join(directory, f)
>                for f in fileList
>                 if os.path.splitext(f)[1] 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
>
> 问题见上述注释!!!
>
> 多谢!!多谢!!!
>
>  ------------------------------
>  zhbguan
> 2007-01-30
>
> _______________________________________________
> python-chinese
> Post: send python-chinese在lists.python.cn
> Subscribe: send subscribe to python-chinese-request在lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request在lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>



-- 
Linker M Lin
linkerlin88在gmail.com
  ※※※※※※※※※
  ※※我思故我在※※
  ※※※※※※※※※
-------------- 下一部分 --------------
一个HTML附件被移除...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/4e205955/attachment-0001.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 10:02

zhbguan zhbguan在lemote.com
星期四 二月 1 10:02:52 HKT 2007

ÄÇôµ÷ÓÃFileInfo.__init__º¯ÊýÖУ¬selfÖ¸ÕëÖ¸µÄÊÇÄĸöʵÀý¶ÔÏóÄØ£¿Õâ¸öÓ¦¸ÃÖ¸µÄÊÇMP3FileInfoµÄʵÀý¶ÔÏó°É£¿£¿
ÁíÍ⣬Èç¹ûÏëÒªÑéÖ¤ËüµÄ»°£¬Ö»ÐèÒª¿´Ò»ÏÂÕâ¸öʵÀý¶ÔÏóµÄÄÚ´æµØÖ·¡£ÄÇÔõô¿ÉÒÔ¿´Ò»ÏÂËüµÄÄÚ´æµØÖ·ÄØ£¿£¿
лл£¡£¡




zhbguan
2007-02-01



·¢¼þÈË£º Linker Lin
·¢ËÍʱ¼ä£º 2007-02-01 09:35:59
ÊÕ¼þÈË£º zhbguan在lemote.com; python-chinese在lists.python.cn
³­ËÍ£º 
Ö÷Ì⣺ Re:_[python-chinese]_DiveIntoPythonÀý³Ì²»½â£¡

Python»áÏÈÔÚ±¾Àà¶ÔÏóµÄº¯Êý±íÖвéÕÒ£¬
ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£



On 2/1/07, zhbguan <zhbguan在lemote.com> wrote:
DiveIntoPython5.4ÖУ¬ÆäÖÐÒ»¸öÀý³ÌΪfileinfo.py£º

"""Framework for getting filetype-specific metadata.Instantiate appropriate class with filename.  Returned object acts like adictionary, 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 osimport sysfrom UserDict import UserDictdef 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   ###´Ë´¦MP3FileInfoµÄÒ»¸öʵÀýµ÷ÓÃÁ˸¸ÀàFileInfoµÄ__int__º¯Êý£¬
                                  ###µ«ÊÇ£¬self["name"] = filenameÔõô»áµ÷ÓÃMP3FileInfoÀàµÄ__setitem__º¯ÊýÄØ£¿£¿
                                  ###´Ë´¦ÎÒÖªµÀ£¬__setitem__ÊÇרÓú¯Êý£¬Ò²¾ÍÊÇ˵£¬Èç¹û³öÏÖ¸³ÖµµÄÇé¿ö£¬ÏµÍ³»á×Ô¶¯µ÷ÓÃÕâ¸öº¯ÊýµÄ¡£

                                  ###ÎÒµÄÎÊÌâÊÇ£º¾ÍÊǵ÷ÓõĻ°£¬Ò²Ó¦¸Ãµ÷ÓÃFileInfoµÄ__setitem__º¯Êý°É£¿£¿´Ë´¦selfÊÇÖ¸ÄǸöʵÀý¶ÔÏó°¡£¿
                                  ###ÊÇÖ¸MP3FileInfoµÄʵÀý¶ÔÏóô£¿£¿£¿

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"
    fileList = [os.path.normcase(f)
                for f in os.listdir(directory)]               fileList = [os.path.join(directory, f)                for f in fileList                if
 os.path.splitext(f)[1] 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
ÎÊÌâ¼ûÉÏÊö×¢ÊÍ£¡£¡£¡

¶àл£¡£¡¶àл£¡£¡£¡




zhbguan
2007-01-30

_______________________________________________
python-chinese
Post: send python-chinese在lists.python.cn 
Subscribe: send subscribe to python-chinese-request在lists.python.cn
Unsubscribe: send unsubscribe to   python-chinese-request在lists.python.cn
Detail Info: http://python.cn/mailman/listinfo/python-chinese




-- 
Linker M Lin
linkerlin88在gmail.com
  ¡ù¡ù¡ù¡ù¡ù¡ù¡ù¡ù¡ù
  ¡ù¡ùÎÒ˼¹ÊÎÒÔÚ¡ù¡ù
  ¡ù¡ù¡ù¡ù¡ù¡ù¡ù¡ù¡ù 
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/9377c9da/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 10:22

Border borderj在gmail.com
星期四 二月 1 10:22:58 HKT 2007

Linker Lin:
"ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£"
ÖеÄ"Ïò±±²éÕÒ"²»Ã÷°×ÊÇʲôÒâ˼,ÄܽâÊÍÒ»ÏÂÂð?


On 1/31/07, Linker Lin <linkerlin88在gmail.com> wrote:
>
> Python»áÏÈÔÚ±¾Àà¶ÔÏóµÄº¯Êý±íÖвéÕÒ£¬
> ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£
>
>


-- 
Border
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070131/b2bebe65/attachment.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 10:25

Zoom.Quiet zoom.quiet在gmail.com
星期四 二月 1 10:25:19 HKT 2007

On 2/1/07, Border <borderj在gmail.com> wrote:
> Linker Lin:
> "找不到会顺着继承树向北查找。"
> 中的"向北查找"不明白是什么意思,能解释一下吗?
>
上北下南…………咔咔咔!

Python 的域设计是通常的思路没有什么不同的

>
>  On 1/31/07, Linker Lin <linkerlin88在gmail.com> wrote:
> > Python会先在本类对象的函数表中查找,
> > 找不到会顺着继承树向北查找。
> >
> >
>
>
>
> --
> Border
> _______________________________________________
> python-chinese
> Post: send python-chinese在lists.python.cn
> Subscribe: send subscribe to
> python-chinese-request在lists.python.cn
> Unsubscribe: send unsubscribe to
> python-chinese-request在lists.python.cn
> Detail Info:
> http://python.cn/mailman/listinfo/python-chinese
>


-- 
'''Time is unimportant, only life important!
http://zoomquiet.org
blog在http://blog.zoomquiet.org/pyblosxom/
wiki在http://wiki.woodpecker.org.cn/moin/ZoomQuiet
scrap在http://floss.zoomquiet.org
douban在http://www.douban.com/people/zoomq/
____________________________________
Pls. use OpenOffice.org to replace M$ Office.
     http://zh.openoffice.org
Pls. use 7-zip to replace WinRAR/WinZip.
     http://7-zip.org/zh-cn/
You can get the truely Freedom 4 software.
'''

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 10:39

yi huang yi.codeplayer在gmail.com
星期四 二月 1 10:39:54 HKT 2007

id(obj)

-- 
http://codeplayer.blogspot.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/63138ac8/attachment.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 11:07

Maconel maconel在21cn.com
星期四 二月 1 11:07:45 HKT 2007

Border£¬ÄúºÃ£¡ 

¡¡¡¡Éϱ±ÏÂÄÏ£¬Ïò±±²éÕÒ£¬¾ÍÊÇÏòÉϲéÕÒß¡£

======== 2007-02-01 10:48:12 ÄúÔÚÀ´ÐÅÖÐдµÀ£º ========

Linker Lin:
"ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£"
ÖеÄ"Ïò±±²éÕÒ"²»Ã÷°×ÊÇʲôÒâ˼,ÄܽâÊÍÒ»ÏÂÂð?



On 1/31/07, Linker Lin <linkerlin88在gmail.com> wrote:
Python»áÏÈÔÚ±¾Àà¶ÔÏóµÄº¯Êý±íÖвéÕÒ£¬
ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£





-- 
Border 

= = = = = = = = = = = = = = = = = = = = = = 
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ÖÂ
Àñ£¡

¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡Maconel
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡maconel在21cn.com
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡2007-02-01
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/cb95425e/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 11:12

zhbguan zhbguan在lemote.com
星期四 二月 1 11:12:54 HKT 2007

ͬ־ÃÇ£¬²»ÒªÅÜÌ⣬ºÃ²»ºÃ°¡£¿
Òª»Ø´ðÎÒµÄÎÊÌâ°¡£¡
лл£¡£¡£¡




zhbguan
2007-02-01



·¢¼þÈË£º Maconel
·¢ËÍʱ¼ä£º 2007-02-01 11:07:49
ÊÕ¼þÈË£º python-chinese在lists.python.cn
³­ËÍ£º 
Ö÷Ì⣺ Re: [python-chinese]DiveIntoPythonÀý³Ì²»½â£¡

Border£¬ÄúºÃ£¡ 

¡¡¡¡Éϱ±ÏÂÄÏ£¬Ïò±±²éÕÒ£¬¾ÍÊÇÏòÉϲéÕÒß¡£

======== 2007-02-01 10:48:12 ÄúÔÚÀ´ÐÅÖÐдµÀ£º ========

Linker Lin:
"ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£"
ÖеÄ"Ïò±±²éÕÒ"²»Ã÷°×ÊÇʲôÒâ˼,ÄܽâÊÍÒ»ÏÂÂð?



On 1/31/07, Linker Lin <linkerlin88在gmail.com> wrote: 
Python»áÏÈÔÚ±¾Àà¶ÔÏóµÄº¯Êý±íÖвéÕÒ£¬
ÕÒ²»µ½»á˳׿̳ÐÊ÷Ïò±±²éÕÒ¡£





-- 
Border 

= = = = = = = = = = = = = = = = = = = = = = 
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ÖÂ
Àñ£¡

¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡Maconel
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡maconel在21cn.com
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡2007-02-01
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/eae429dd/attachment.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 11:18

Zoom.Quiet zoom.quiet在gmail.com
星期四 二月 1 11:18:51 HKT 2007

On 2/1/07, zhbguan <zhbguan在lemote.com> wrote:
>
>
> DiveIntoPython5.4中,其中一个例程为fileinfo.py:
>
> """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
> ###此处MP3FileInfo的一个实例调用了父类FileInfo的__int__函数,
>  ###但是,self["name"] =
> filename怎么会调用MP3FileInfo类的__setitem__函数呢??
>  ###此处我知道,__setitem__是专用函数,也就是说,如果出现赋值的情况,系统会自动调用这个函数的。
> ###我的问题是:就是调用的话,也应该调用FileInfo的__setitem__函数吧??此处self是指那个实例对象啊?
>  ###是指MP3FileInfo的实例对象么???
是也乎,理解正确,
从类里面的函式声明也可以看出来,这些 self 不过是代记符,
是等待实例化后,才真正可用的 "自个儿"

> 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"
>  fileList = [os.path.normcase(f)
>  for f in os.listdir(directory)]
>  fileList = [os.path.join(directory, f)
>  for f in fileList
>  if os.path.splitext(f)[1] 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
>
> 问题见上述注释!!!
>
> 多谢!!多谢!!!
>
>  ________________________________
>
> zhbguan
> 2007-01-30
> _______________________________________________
> python-chinese
> Post: send python-chinese在lists.python.cn
> Subscribe: send subscribe to
> python-chinese-request在lists.python.cn
> Unsubscribe: send unsubscribe to
> python-chinese-request在lists.python.cn
> Detail Info:
> http://python.cn/mailman/listinfo/python-chinese
>


-- 
'''Time is unimportant, only life important!
http://zoomquiet.org
blog在http://blog.zoomquiet.org/pyblosxom/
wiki在http://wiki.woodpecker.org.cn/moin/ZoomQuiet
scrap在http://floss.zoomquiet.org
douban在http://www.douban.com/people/zoomq/
____________________________________
Pls. use OpenOffice.org to replace M$ Office.
     http://zh.openoffice.org
Pls. use 7-zip to replace WinRAR/WinZip.
     http://7-zip.org/zh-cn/
You can get the truely Freedom 4 software.
'''

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 12:21

yi huang yi.codeplayer在gmail.com
星期四 二月 1 12:21:44 HKT 2007

On 2/1/07, zhbguan <zhbguan at lemote.com> wrote:
>
>  DiveIntoPython5.4中,其中一个例程为fileinfo.py:
>
>
> """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 osimport sysfrom 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   ###此处MP3FileInfo的一个实例调用了父类FileInfo的__int__函数,
>
>                                   ###但是,self["name"] = filename怎么会调用MP3FileInfo类的__setitem__函数呢??
>
>                                   ###此处我知道,__setitem__是专用函数,也就是说,如果出现赋值的情况,系统会自动调用这个函数的。
>
>                                   ###我的问题是:就是调用的话,也应该调用FileInfo的__setitem__函数吧??此处self是指那个实例对象啊?
>
>                                   ###是指MP3FileInfo的实例对象么???
>
> 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"
>     fileList = [os.path.normcase(f)
>                 for f in os.listdir(directory)]
>     fileList = [os.path.join(directory, f)
>                for f in fileList
>                 if os.path.splitext(f)[1] 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
>
> 问题见上述注释!!!
>
> 多谢!!多谢!!!
>
>  ------------------------------
>  zhbguan
> 2007-01-30
>



多态,多态啊兄弟!
info = MP3FileInfo(...)
self 就是 MP3FileInfo 的实例
info = FileInfo(...)
self  就是 FileInfo 的实例

-- 
http://codeplayer.blogspot.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/f9adae73/attachment.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年02月01日 星期四 13:26

Linker Lin linkerlin88在gmail.com
星期四 二月 1 13:26:15 HKT 2007

On 2/1/07, zhbguan <zhbguan在lemote.com> wrote:
>
>  那么调用FileInfo.__init__函数中,self指针指的是哪个实例对象呢?这个应该指的是MP3FileInfo的实例对象吧??
> 另外,如果想要验证它的话,只需要看一下这个实例对象的内存地址。那怎么可以看一下它的内存地址呢??
> 谢谢!!
>

不是这样理解的。
FileInfo.__init__()调用的时候,.前面是类名,python不会自动填上第一个默认的self参数,所以要手动填写

FileInfo.__setitem__(self, key, item)

这里的self就是函数参数列表的那个self:

def __setitem__(self, key, item):


Python提供了一种语法上的甜点,当你用 obj_name.func()时,第一个参数就是 obj_name,等价于:
 obj_name.func(obj_name)

而func的定义:
def func(self):
    pass

self此时就是 obj_name。
当你用类名调用的时候,没有办法自动填写self,所以需要手动填写一下。
顺便提一下,这也为实现单例模式提供了便利。

------------------------------
>  zhbguan
> 2007-02-01
>  ------------------------------
>  *发件人:* Linker Lin
> *发送时间:* 2007-02-01 09:35:59
> *收件人:* zhbguan在lemote.com; python-chinese在lists.python.cn
> *抄送:*
> *主题:* Re:_[python-chinese]_DiveIntoPython例程不解!
>
> Python会先在本类对象的函数表中查找,
> 找不到会顺着继承树向北查找。
>
>
> On 2/1/07, zhbguan <zhbguan在lemote.com> wrote:
> >
> >   DiveIntoPython5.4中,其中一个例程为fileinfo.py:
> >
> >
> > """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   ###此处MP3FileInfo的一个实例调用了父类FileInfo的__int__函数,
> >
> >                                   ###但是,self["name"] = filename怎么会调用MP3FileInfo类的__setitem__函数呢??
> >
> >                                   ###此处我知道,__setitem__是专用函数,也就是说,如果出现赋值的情况,系统会自动调用这个函数的。
> >
> >                                   ###我的问题是:就是调用的话,也应该调用FileInfo的__setitem__函数吧??此处self是指那个实例对象啊?
> >
> >                                   ###是指MP3FileInfo的实例对象么???
> >
> > 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"
> >     fileList = [os.path.normcase(f)
> >                 for f in os.listdir(directory)]
> >     fileList = [os.path.join(directory, f)
> >                for f in fileList
> >                 if
> >  os.path.splitext(f)[1] 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
> >
> >  问题见上述注释!!!
> >
> >  多谢!!多谢!!!
> >
> >  ------------------------------
> >  zhbguan
> >  2007-01-30
> >
> > _______________________________________________
> > python-chinese
> > Post: send python-chinese在lists.python.cn
> > Subscribe: send subscribe to python-chinese-request在lists.python.cn
> > Unsubscribe: send unsubscribe to
> > python-chinese-request在lists.python.cn
> > Detail Info: http://python.cn/mailman/listinfo/python-chinese
> >
>
>
>
> --
> Linker M Lin
> linkerlin88在gmail.com
>   ※※※※※※※※※
>   ※※我思故我在※※
>   ※※※※※※※※※
>



-- 
Linker M Lin
linkerlin88在gmail.com
  ※※※※※※※※※
  ※※我思故我在※※
  ※※※※※※※※※
-------------- 下一部分 --------------
一个HTML附件被移除...
URL: http://python.cn/pipermail/python-chinese/attachments/20070201/c6ea463f/attachment-0001.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号