[Tutor] How to reuse code in Python
Kent Johnson
kent37 at tds.net
Tue Nov 29 12:00:59 CET 2005
Negroup - wrote:
> Hi.
> Suppose that I need to use in my project a module that belongs to
> another project, because - with some tuning - it can fit my needings.
>
> module.py
> limit = 30
>
> class A:
> def __init__(self):
> self.num = 20
> def info(self):
> return limit
> def inc_num(self):
> self.num += 1
> def check(self):
> return self.num > limit
>
> Now suppose that I'd like to have the same class A in my module, but
> also I want that the initial value of limit is set to 25.
>
>
>>>>limit = 25
>>>>from module import A
>>>>a = A()
>>>>a.info()
>
> 30
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.
Another way to do this is to make limit a class attribute. Then you can change it in subclasses:
class A:
limit = 25
def __init__(self):
self.num = 20
def info(self):
return self.limit
def inc_num(self):
self.num += 1
def check(self):
return self.num > self.limit
class B(A):
limit = 30
a = A()
a.info() --> 25
b = B()
b.info() --> 30
Kent
Note you still refer to self.limit so the value of limit in the current class will be found.
> where is the value 30 coming from?
from module.limit.
Kent
--
http://www.kentsjohnson.com
More information about the Tutor
mailing list