[Tutor] How to reuse code in Python
Negroup -
negroup at gmail.com
Tue Nov 29 13:20:16 CET 2005
2005/11/29, Kent Johnson <kent37 at tds.net>:
> Negroup - wrote:
[cut]
> Obviously this doesn't do what you want. The problem is that class A is seeing the limit defined in it's module. 'global' variables in Python actually have module scope, there is no truly global scope in Python (OK, there's the __builtin__ scope, but this is a beginner's list!)
> IMO the best solution is to pass limit as a parameter to A's constructor and save it as an instance attribute:
>
> class A:
> def __init__(self, limit):
> self.limit = limit
> self.num = 20
> def info(self):
> return self.limit
> def inc_num(self):
> self.num += 1
> def check(self):
> return self.num > self.limit
>
> Now you can create whatever kind of A's you want:
> from module import A
> a = A(30)
> etc.
This is true. However following this approach I have touched the code
in module.py (the original), and I'd avoid to do that.
>
> Another way to do this is to make limit a class attribute. Then you can change it in subclasses:
Idem
[cut]
A way I found is to import module directly and then simply assign to
it the property limit:
>>> import module
>>> module.limit = 25
>>> a = module.A()
>>> b = module.A()
(25, 25)
This however has a side effect (that luckily is not a big problem,
because I don't need to change limit after the first time):
>>> module.limit = 26
>>> a.info(), b.info()
(26, 26)
> > where is the value 30 coming from?
>
> from module.limit.
I have some difficulties understanding this. In my previous post the
syntax is: from module import A and so 'module' is not imported.
Thanks for your attention
More information about the Tutor
mailing list