coding style - (Usage of Class Variables) Pythonic - or nasty habit learnt from java? -
hello pythoneers: following code mock of i'm trying do, should illustrate question.
i know if dirty trick picked java programming, or valid , pythonic way of doing things: i'm creating load of instances, need track 'static' data of instances created.
class myclass: counter=0 last_value=none def __init__(self,name): self.name=name myclass.counter+=1 myclass.last_value=name
and output of using simple class , showing working expected:
>>> x=myclass("hello") >>> print x.name hello >>> print myclass.last_value hello >>> y=myclass("goodbye") >>> print y.name goodbye >>> print x.name hello >>> print myclass.last_value goodbye
so acceptable way of doing kind of thing, or anti-pattern ?
[for instance, i'm not happy can apparently set counter both within class(good) , outside of it(bad); not keen on having use full namespace 'myclass' within class code - looks bulky; , lastly i'm setting values 'none' - i'm aping static-typed languages doing this?]
i'm using python 2.6.2 , program single-threaded.
you can solve problem splitting code 2 separate classes.
the first class object trying create:
class myclass(object): def __init__(self, name): self.name = name
and second class create objects , keep track of them:
class myclassfactory(object): counter = 0 lastvalue = none @classmethod def build(cls, name): inst = myclass(name) cls.counter += 1 cls.lastvalue = inst.name return inst
this way, can create new instances of class needed, information created classes still correct.
>>> x = myclassfactory.build("hello") >>> myclassfactory.counter 1 >>> myclassfactory.lastvalue 'hello' >>> y = myclassfactory.build("goodbye") >>> myclassfactory.counter 2 >>> myclassfactory.lastvalue 'goodbye' >>> x.name 'hello' >>> y.name 'goodbye'
finally, approach avoids problem of instance variables hiding class variables, because myclass instances have no knowledge of factory created them.
>>> x.counter traceback (most recent call last): file "<stdin>", line 1, in <module> attributeerror: 'myclass' object has no attribute 'counter'
Comments
Post a Comment