[Tutor] How to reuse code in Python
Negroup -
negroup at gmail.com
Tue Nov 29 11:10:55 CET 2005
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.
This is what I mean, with an example:
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
Now I have a couple of questions.
The most important: how to reuse the class A in my module? "class A"
is not short and I think that copy/paste, then apply changes, wouldn't
be a valid solution!
This is the second question, more for curiosity than for real necessity, anyway:
Considering that:
>>> limit # Obvious
25
>>> print a.limit # Obvious
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'limit'
>>> print A.limit # Obvious
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: class A has no attribute 'limit'
where is the value 30 coming from?
Thanks, dear tutors!
More information about the Tutor
mailing list