python核心编程第13章代码例子twrapme.py的疑问?
PHP中文网
PHP中文网 2017-04-18 09:40:31
0
1
245

授权之后,声明一个示例t,实例中属性_TimedWrapMe__mtime是怎么来的?
书中源程序:


from time import time, ctime

class TimedWrapMe(object):
    def __init__(self, obj):
        self.__data = obj
        self.__ctime = self.__mtime = self.__atime = time()

    def get(self):
        self.__atime = time()
        return self.__data

    def gettimeval(self, t_type):
        if not isinstance(t_type, str) or \
                t_type[0] not in 'cma':
            raise TypeError, \
                "argument of 'c', 'm', or 'a' req'd"
        return getattr(self, '_%s__%stime' % \
                       (self.__class__.__name__, t_type[0]))

    def gettimestr(self, t_type):
        return ctime(self.gettimeval(t_type))

    def set(self, obj):
        self.__data = obj
        self.__mtime = self.__atime = time

    def __repr__(self):
        self.__atime = time()
        return 'self.__data'

    def __str__(self):
        self.__atime = time()
        return str(self.__data)

    def __getattr__(self, attr):
        self.__atime = time()
        return getattr(self.__data, attr)


>>> from twrapme import TimedWrapMe
>>> t = TimedWrapMe(923)
>>> dir(t)
['_TimedWrapMe__atime', '_TimedWrapMe__ctime', '_TimedWrapMe__data', '_TimedWrapMe__mtime', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get', 'gettimestr', 'gettimeval', 'set']
PHP中文网
PHP中文网

认证高级PHP讲师

Antworte allen(1)
小葫芦

https://docs.python.org/2/tut...

Python内部的私有变量(下划线开头的变量)不是真的私有变量

举个文档里的例子

__spam

被处理成了公有变量
_类名__spam

同理
_TimedWrapMe__mtime来自__mtime也就是 self.__ctime = self.__mtime = self.__atime = time()这句来的

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage