相关疑难解决方法(0)

如何适应Singleton模式?(弃用警告)

几年前,我在Duncan Booth的 Python中找到了Singleton模式的实现:

class Singleton(object):
    """
    Singleton class by Duncan Booth.
    Multiple object variables refers to the same object.
    http://web.archive.org/web/20090619190842/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#singleton-and-the-borg
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(
                               cls, *args, **kwargs)
        return cls._instance
Run Code Online (Sandbox Code Playgroud)

问题还描述了" 在Python中定义单例的简单,优雅的方法吗? "

我通过子类别使用Singleton:
class Settings(Singleton)
class Debug(Singleton)

最近我对程序做了一些修改并得到了这个警告:

/media/KINGSTON/Sumid/src/miscutil.py:39: DeprecationWarning: 
object.__new__() takes no parameters
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我找到了关于弃用的解释(由Guido 解释),__new__其中说参数根本没有使用.传递不需要的参数可能是错误的症状.

所以我决定清除参数:

class Singleton(object):
_instance = None

def __new__(cls):
    if not cls._instance: …
Run Code Online (Sandbox Code Playgroud)

python singleton design-patterns deprecated

15
推荐指数
1
解决办法
3955
查看次数

什么可能导致python模块导入两次?

据我所知,python模块永远不会导入两次,即模块中的代码仅在第一次导入时执行.后续导入语句只是将模块添加到导入范围.

我有一个名为"TiledConvC3D.py"的模块,但似乎已多次导入.我使用pdb打印此模块代码顶部的堆栈.

这是从第一次执行模块开始的堆栈跟踪结束:

File "<anonymized>/python_modules/Theano/theano/gof/cmodule.py", line 328, in refresh
  key = cPickle.load(open(key_pkl, 'rb'))
File "<anonymized>/ops/TiledConvG3D.py", line 565, in <module>
  import TiledConvC3D
File "<anonymized>/ops/TiledConvC3D.py", line 18, in <module>
  pdb.traceback.print_stack()
Run Code Online (Sandbox Code Playgroud)

它继续执行几次.但是,第二次调用它的完整堆栈跟踪没有显示任何调用reload,因此不应发生这些执行:

File "sup_train_conj_grad.py", line 103, in <module>
  dataset = Config.get_dataset(dataset_node)
File "<anonymized>/Config.py", line 279, in get_dataset
  from datasets import NewWiskott
File "<anonymized>/datasets/NewWiskott.py", line 16, in <module>
  normalizer_train = video.ContrastNormalizer3D(sigma, global_per_frame = False, input_is_5d = True)
File "<anonymized>/util/video.py", line 204, in __init__
  self.f = theano.function([input],output)
File "<anonymized>/python_modules/Theano/theano/compile/function.py", line 105, in function …
Run Code Online (Sandbox Code Playgroud)

python import module

14
推荐指数
1
解决办法
6859
查看次数

如何在python中优雅地记录多个非常相似的事件?

使用pythons logging模块,有没有办法将多个事件收集到一个日志条目中?一个理想的解决方案是扩展python的logging模块或自定义格式化程序/过滤器,因此收集相同类型的日志记录事件在后台发生,并且不需要在代码体中添加任何内容(例如,在每次调用日志记录函数时).

这是一个生成大量相同或非常相似的日志记录事件的示例:

import logging

for i in range(99999): 
    try:
        asdf[i]   # not defined!
    except NameError:
        logging.exception('foo') # generates large number of logging events
    else: pass

# ... more code with more logging ...

for i in range(88888): logging.info('more of the same %d' % i)

# ... and so on ...
Run Code Online (Sandbox Code Playgroud)

所以我们有相同的例外99999次并记录它.如果日志只是说:

ERROR:root:foo (occured 99999 times)
Traceback (most recent call last):
  File "./exceptionlogging.py", line 10, …
Run Code Online (Sandbox Code Playgroud)

python logging exception

10
推荐指数
2
解决办法
1204
查看次数

如何避免在python中创建对象?

我是python编程的新手,我有一个类,对于这个类,我创建了一个对象(obj1).i不想创建除此对象之外的其他对象,如果有任何体想要为此类创建一个应该引用的对象到第一个对象(而不是再创建一个对象).如何做到这一点?请参考以下代码?

class MyClass:
   def __init__(self):
      pass
obj1=MyClass()//create object
obj2=MyClass()//avoid creation and refer obj2 to obj1
obj3=MyClass()//avoid creation and refer obj3 to obj1
Run Code Online (Sandbox Code Playgroud)

python python-3.x

6
推荐指数
1
解决办法
1605
查看次数

为"只有一个实例"创建一个Python类?

我问这个关于Python的问题,虽然它可能适用于大多数OOP语言.

当我只期望在任何程序中只使用一次数据模型时,我可以使用类/静态方法和属性创建一个类,或者只创建一个常规类并将其实例化一次并仅使用该一个副本.在这种情况下,哪种方法更好,为什么?

使用python,我还可以编写一个模块并像使用类一样使用它.在这种情况下,哪种方式更好,为什么?

示例:我希望有一个中央数据结构来访问/保存数据到文件.

模块方式:

data.py

attributes = something
...
def save():
...
Run Code Online (Sandbox Code Playgroud)

main.py

import data
data.x = something
...
data.save()
Run Code Online (Sandbox Code Playgroud)

上课方式:

class Data:
    attributes = something
    @classmethod
    def save(cls):

Data.x = something
Data.save()
Run Code Online (Sandbox Code Playgroud)

实例方式

class Data:
    def save(self):

data = Data()
data.x = something
data.save()
Run Code Online (Sandbox Code Playgroud)

python oop

5
推荐指数
1
解决办法
2258
查看次数

Python 中带有子类的单例

最近,我在考虑如何用Python实现单例模式。如果 Singleton 类没有子类,下面的代码可以正常工作。

class Singleton(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance
Run Code Online (Sandbox Code Playgroud)

但是,Singleton 类可能有子类。

class SingletonSub1(Singleton):
    def __new__(cls, *args, **kwargs):
        return super(SingletonSub1, cls).__new__(cls, *args, **kwargs)

class SingletonSub2(Singleton):
    def __new__(cls, *args, **kwargs):
        return super(SingletonSub1, cls).__new__(cls, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

要求是系统中只能有 1 个实例,即 Singleton、SingletonSub1 或 SingletonSub2。我怎样才能实现这个?我知道我绝对可以使用模块级变量来保存 Singleton 对象。但这确实是一个糟糕的代码......

python singleton subclass

5
推荐指数
1
解决办法
3018
查看次数

python:具有staticmethods的类vs具有全局变量的模块

我正在研究这个Python模块,它由几个文件组成.这些文件实际上很少是独立的,并且意味着要做一个非常具体的工作.我知道这样一个事实:这些文件只有一个实例(模块?),而且不多,因为这种工作是顺序的,只需要一次.

让我们以CXXParser我目前正在构建的这个模块为例:

例程简单明了 - 获取c ++文件,解析它,并将其"转换"为其他内容.由于我来自c ++世界,我立即开始在Python中寻找静态方法和单例.对于这个例子的使用,我有'public' parse函数,以及这个模块的许多'内部'函数,它实际上解析了文件.

我想知道,"Pythonic"的做法是什么?我开始四处寻找正确的方法,但只是感到困惑.因为我想到了单身 - 我看到了这个问题,并且从阅读答案开始,我开始在模块级实现它.但是,再一次,我观看Python核心开发人员Raymond Hettinger的几个视频,并且他提到 - 几次 - 全局变量都很糟糕,并且最好使用类级变量.

这些是我目前面临的两个选择:

A.使用classmethods类:

#cxxparser.py
class CXXParser(object):
    filename = ''
    cflags   = ''
    translation_unit = None

    def __init__(self, filename, cflags = None):
        super(CXXParser, self).__init__()
        filename = filename
        if cflags:
             cflags = cflags

    @classmethod
    def get_tu(cls):
        'get the tu from the file'
        return tu

    @classmethod
    def parse(cls):
        ...
        #call some inner functions
        #for example:
        translation_unit = cls.get_tu() …
Run Code Online (Sandbox Code Playgroud)

python singleton static-methods module global-variables

5
推荐指数
1
解决办法
560
查看次数

为什么这个单例实现"不是线程安全的"?

1. @Singleton装饰

我找到了一种优雅的方法来装饰Python类来实现它singleton.该类只能生成一个对象.每次Instance()调用都返回相同的对象:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Also, the decorated class cannot be
    inherited from. Other than that, there are no restrictions that apply
    to the decorated class.

    To get the singleton instance, use the …
Run Code Online (Sandbox Code Playgroud)

python singleton multithreading python-3.x python-3.6

5
推荐指数
2
解决办法
4507
查看次数

从不同的模块导入类的实例

我有一个名为directory的模块和另一个名为species的模块.无论我有多少种,总会有一个目录.

在目录模块中,我有1个目录类.在物种模块内部,我有许多不同的物种类别.

#module named directory
class directory:

    def __init__(self):
        ...

    def add_to_world(self, obj, name, zone = 'forrest', space = [0, 0]):
        ...


#module named species
class Species (object):

def __init__(self, atlas):
    self.atlas = atlas

def new(self, object_species, name, zone = 'holding'):
    self.object_species = object_species
    self.name = name
    self.zone = zone
    self.atlas.add_to_world(object_species, name)

class Lama(Species):

def __init__(self, name, atlas, zone = 'forrest'):
    self.new('Lama', name)
    self.at = getattr(Entity, )
    self.atlas = atlas
Run Code Online (Sandbox Code Playgroud)

问题是,在我的每个类中,我必须将atlas对象传递给该物种.我怎样才能告诉物种从不同的模块中获取实例.

例如,如果我在一个名为Entity的模块中有一个'atlas'实例,并且有一个Entity类,我怎么能用几行代码告诉所有物种从Entity中获取该实例?

python

3
推荐指数
1
解决办法
5677
查看次数

如何初始化Singleton派生对象一次

可能重复:
在Python中定义单例是否有简单,优雅的方法?

我有以下示例代码,其中我从Singleton派生一个类(希望它是一个):

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance

class Tracer(Singleton):         
    def __init__(self):
        print "Init"

a = Tracer()
b = Tracer()
Run Code Online (Sandbox Code Playgroud)

当你尝试它时,你会看到再次调用__init__方法Tracer.是不是有单身人士让另一个实例引用原始实例?我不想__init__再次运行该方法,因为它可能会覆盖以前的信息.也许单身人士是错的还是有用的?

python singleton

2
推荐指数
1
解决办法
1595
查看次数