Set static attributes...maybe.
Beppe
giuseppecostanzi at gmail.com
Mon Aug 18 13:33:39 EDT 2014
Il giorno lunedì 18 agosto 2014 19:13:08 UTC+2, Chris Kaynor ha scritto:
> On Mon, Aug 18, 2014 at 10:00 AM, Beppe <giuseppe... at gmail.com> wrote:
>
>
> hi to everybody,
>
> in the following scrip I try to call the function read_parameters () but returns me that wants two arguments!?!?!
>
> My intent is to have in the class, Engine (), some static attributes that can be used by other instances without to redefine this every time.
>
> These matters could be for example a path or a connection to a database.
>
> suggestions?
>
>
>
> regards
>
> beppe
>
>
>
> class Master(object):
>
> def __init__(self,):
>
> pass
>
>
>
> class Engine(Master):
>
> dict_parameters = {}
>
> def __init__(self,):
>
> super(Engine, self).__init__()
>
>
>
> @staticmethod
>
> def read_parameters(self,path):
>
>
>
> self.dict_parameters = {1:"a",2:"b"}
>
>
>
> What you probably want here, based on your description is (untested):
> @classmethod
> def read_parameters(cls, path): # Note, the name is "cls". This is not required, but is convention, similar to "self".
>
>
> cls.dict_parameters = {1:"a",2:"b"}
>
>
> @staticmethod creates a method that does not receive any special parameter, so the signature would be "def read_parameters(path)".
>
>
>
>
>
> Note that, personally, I would name the method "parse_parameters" to make it clearer what it does.
>
>
>
>
>
> def check_parameters(self):
>
> self.read_parameters("hello_world")
Perfet,
class Master(object):
def __init__(self,):
pass
class Engine(Master):
def __init__(self,):
super(Engine, self).__init__()
@classmethod
def parse_parameters(cls, path):
cls.dict_parameters = {1:"a",2:"b"}
def check_parameters(self):
self.parse_parameters("hello_world")
def __str__(self):
return "dict_parameters: %s" % self.dict_parameters
foo = Engine()
foo.check_parameters()
bar = Engine()
foobar = Engine()
print foo
print bar
print foobar
IDLE 2.6.6 ==== No Subprocess ====
>>>
dict_parameters: {1: 'a', 2: 'b'}
dict_parameters: {1: 'a', 2: 'b'}
dict_parameters: {1: 'a', 2: 'b'}
thanks a lot Chris
More information about the Python-list
mailing list