0

This question may look silly(since I am new to python), but can you guys tell me what is the difference between self and classname when Binding?

class OnlyOne(object):

  class __OnlyOne:
    def __init__(self):
       self.val = None

    def __str__(self):
       return ´self´ + self.val

 instance = None

 def __new__(cls): # __new__ always a classmethod
    if not OnlyOne.instance:
      OnlyOne.instance = OnlyOne.__OnlyOne()
            return OnlyOne.instance

 def __getattr__(self, name):
     return getattr(self.instance, name)

 def __setattr__(self, name):
      return setattr(self.instance, name)

Here, I usually use Instance as self... What is the difference between using self and Only one... my intuition tells me that, it is a global variable.... if it is a global variable, it does not make sense at all(I will edit this, if its a global variable). Thanks!!

4

1 回答 1

0

好的,我想我已经掌握了您的代码......它的工作方式是在调用构造函数时:

a = OnlyOne()  #call constructor.  This implicitly calls __new__

此时,__new__检查类以查看是否已创建实例(实例不是无)。如果尚未创建,它会创建一个实例并将其放入instance类属性中。然后instance返回类属性,然后将其作为self.

我认为,如果你真的需要一个单例,那么你的程序设计就有些可疑(懒惰)。单例允许信息以奇怪的方式在整个程序中传播(想象一下创建 . 实例的函数foobar两者都在调用时显示OnlyOne您所做的更改)——这有点类似于猴子补丁。foobar

如果在重新考虑你的设计几个月后,你决定你真的需要一个单例,你可以创建某种更透明的工厂类......

于 2012-07-27T00:31:25.667 回答