Borg Design with New Style Classes

I stumbled upon a Borg design and thought it would fit in well with what I was doing, however I get DeprecationWarning when using it (I am using Python 2.6 now, but will be upgrading soon).

New version found in comments:

 class Borg(object): _state = {} def __new__(cls, *p, **k): self = object.__new__(cls, *p, **k) self.__dict__ = cls._state return self 

However, when you create an instance with arguments, you get DepricationWarning :

 DepricationWarning: object.__new__() takes no parameters 

Is there a way to use a Borg project without using object.__new__() with arguments?

+4
source share
1 answer

You do not need to pass arguments to __new__ , they are automatically passed to __init__ . object.__new__ does not use these arguments. Here the man himself says about this:

It makes no sense to call a .__ new __ () object with a parameter of more than a class, and any code that did this just dumped these arguments into a black hole.

So just do it instead:

 class Borg(object): _state = {} def __new__(cls, *p, **k): self = object.__new__(cls) self.__dict__ = cls._state return self def __init__(self, foo): print(foo) 

Check this:

 >>> import borg >>> b = borg.Borg(foo='bar') bar 

(Tested only with 2.7, if it works with 2.6).

+5
source

Source: https://habr.com/ru/post/1392750/


All Articles