visibility between modules
Mike Meyer
mwm at mired.org
Sat Apr 9 17:47:31 EDT 2005
"max(01)*" <max2 at fisso.casa> writes:
> hi.
>
> if i have a single program file, different class instances can share
> information in (at least) two fashions:
>
> 1. using instance variables:
>
> class AClass:
> def __init__(self):
> self.att_1 = 42
> self.att_2 = "Hello!"
>
> class AnotherClass:
> def __init__(self):
> self.att_1 = anInstanceOfAClass.att_1
>
> anInstanceOfAClass = AClass()
> anInstanceOfAnotherClass = AnotherClass()
> print anInstanceOfAnotherClass.att_1 ### This should print out 42
>
> 2. using globals:
>
> class AClass:
> def __init__(self):
> self.att_1 = 42
> self.att_2 = "Hello!"
>
> class AnotherClass:
> pass
>
> aGlobalString = "No way."
> anInstanceOfAClass = AClass()
> anInstanceOfAClass.att2 = aGlobalString
> anInstanceOfAnotherClass = AnotherClass()
> anInstanceOfAnotherClass.att_1 = aGlobalString
> print anInstanceOfAClass.att2 ### This should output "No way."
> print anInstanceOfAnotherClass.att_1 ### And this too
Both these methods actually use globals. In ther first case, the
global is "anInstanceOfAClass", that is bound to self.att_1 in the
__init__ method of AnotherClass.
The solution is to pass the instance in as a parameter:
class AClass:
def __init__(self):
self.att_1 = 42
self.att_2 = "Hello!"
class AnotherClass:
def __init__(self, instance):
sefl.att_1 = instance
anInstanceOfAClass = AClass()
anInstanceOfAnotherClass = AnotherClass(anInstanceOfAClass)
or maybe just:
anInstaceOfAnotherClass = AnotherClass(AClass())
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list