Storing parameters in a class, and how to access them
I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often) depth, ratio, method and riddle are other values needed.
I put these in a class so they'd be in one place, where I can go to change them. Is this the best pythonic way to do this? It seems that I can't refer to them by Params.depth. This produces the error 'Params has no attribute 'depth'. I have to create an instance of Params() (p = Params()) and refer to them 开发者_如何学运维by p.depth.
I'm faily new to Python. Thanks
class Params(object):
def __init__(self):
object.__init__(self)
self.atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x']
self.operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2}
self.depth = 1
self.ratio = .4
self.method = ''
self.riddle = '1 + np.sin(x)'
What you have there are object properties. You mean to use class variables:
class Params(object):
atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x']
operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2}
depth = 1
ratio = .4
method = ''
riddle = '1 + np.sin(x)'
# This works fine:
Params.riddle
It's fairly common in Python to do this, since pretty much everyone agrees that Params.riddle
is a lot nicer to type than Params['riddle']
. If you find yourself doing this a lot you may want to use this recipe which makes things a bit easier and much clearer semantically.
Warning: if that Params
class gets too big, an older, grumpier Pythonista may appear and tell you to just move all that crap into its own module.
You can do this in a class, but I'd prefer to just put it in a dictionary. Dictionaries are the all-purpose container type in Python, and they're great for this sort of thing.
params = {
atoms: ['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'],
operators: {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2},
depth: 1,
ratio: .4,
method: '',
riddle = '1 + np.sin(x)'
}
Now you can do params['depth']
or params['atoms'][2]
. Admittedly, this is slightly more verbose than the object form, but personally I think it's worth it to avoid polluting the namespace with unnecessary class definitions.
精彩评论