python - Define a constructor in full classmethod class -
let's have following class :
class context: element_list = [] @classmethod def add(cls, element): cls.element_list.append(element) @classmethod def remove(cls, element): cls.element_list.remove(cls.element_list.index(element))
this class near of singleton class. objective update element_list
attribute anywhere in program without passing context
instance parameter of functions.
pycharm signals me should define __init__
method. not want create 2 different instances of class. thinking creating dummy __init__
method :
def __init__(self): raise notimplementederror("this class should not initialized")
the question(s) (are) : should define __init__
method ? if yes how ? instead of using classmethod
implementation should use singleton class (see: is there simple, elegant way define singletons?)
the
__init__
method not mandatory. should define__init__
method if want pass state instance being initialized. looking @ code snippet provided, doesn't seem case.there few ways (hacks) implement singleton pattern in python:
- check out borg pattern
- see stack overflow thread on creating singleton in python
however, think methods aren't pythonic , should avoided majority of cases.
as others have said, use python modules. python modules 1 of awesome features of python programming language. can have state (variables), behaviors (functions) , within 1 python process execution, a module loaded once.
this means that, in directory structure like:
. ├── bar.py ├── foo.py ├── main.py └── singleton.py
you do:
# file: singleton.py element_list = []
and rest of application import , use it:
# file: foo.py import singleton def foo(): # ... complex computations ... singleton.element_list.append('baz')
# file: bar.py import singleton def bar(): # ... more complex things ... if 'baz' in singleton.element_list: print('baz')
# file: main.py import foo import bar foo.foo() bar.bar() # outputs: 'baz'
as can see, besides being simple , more elegant, using module gives usual list utilities interface (for instance,
singleton.element_list[1:]
orsingleton.element_list + ['my', 'other', 'list']
, , on). if wanted way, have implement other classmethods.
Comments
Post a Comment