I've got an app that creates an object in its main class (it also
creates a GUI). My problem is that I need to pass this object, a
list, to a dialog that is implemented as a second class. I want to
edit the contents of that list and then pass back the results to the
first class. So my question is, can a method in one class change an
object in another class?
If the answer is no, I suppose I could pass in the list as an argument
when I create the second class, then return the contents of the list
when I end the methods in that second class.
alternatively, I could make the list a global variable, then it would
be available to all classes. I have a nagging feeling though that
global variables are to be avoided on general principle. Is this
correct?
Here's a simple example app that tries to have one class change the
object in another class. It doesn't give the behaviour I want,
though.
---
#objtest.py
class first:
def __init__(self):
a = 'a'
self.a = a
print self.a
def update(self):
print 'initially, a is', self.a
self.a = second(self.a)
print 'afterwards, a is', self.a
class second:
def __init__(self, a):
pass
def __call__(self, a):
a = 'aa'
return a
if __name__ == '__main__':
app = first()
app.update()
thanks,
--
Stewart Midwinter st*****@midwint er.ca st************* **@gmail.com 5 2066
Here's what I came up with:
#objtest.py
class first:
def __init__(self):
a = 'a'
self.a = a
print self.a
def update(self):
print 'initially, a is', self.a
self.a = second(self.a)
print 'afterwards, a is', self.a.call(sel f.a)
class second:
def __init__(self, a):
pass
def call(self, a):
a = 'aa'
return a
if __name__ == '__main__':
app = first()
app.update()
Not sure if this is what you are wanting though.
> I've got an app that creates an object in its main class (it also creates a GUI). My problem is that I need to pass this object, a list, to a dialog that is implemented as a second class. I want to edit the contents of that list and then pass back the results to the first class. So my question is, can a method in one class change an object in another class?
Sure it can. But your code shows that you suffer from a fundamental
misunderstandin g on how variables and values work in python. Don't be to
worried about that, it happens to quite a few people.
A variable in python is just a name refering to an object. So this a = 'a' b = a print a, b
a a
will make a and b both refer to the string 'a'. Now assigning a different
value to b will not affect the binding of a:
b = 10 print a, b
a 10
So that is the reason you obeserve the behaviour you've seen. Now the
question is how to accomplish your desired goal? The answer is simple:
don't rebind a value to a name - alter the value! In python, there is a
distinction between mutable objects and immutable ones. Strings and numbers
are of the latter kind, lists and dicts and objects of the former. So if we
changed our example slighly, things start working as you'd expect:
a = ['a'] b = a print a,b
['a'] ['a'] b[0] = 10 print a, b
[10] [10]
So if you pass the same _mutable_ object to two objects, and one of them
changes it, the other one will see the changes:
class A:
def __init__(self):
self.a_list = [0]
class B:
def __init__(self, l):
self.l = l
def foo(self):
self.l.append(1 00)
a = A()
b = B(a.a_list)
b.foo()
print a.a_list
-> [0, 100]
There are some resources on the web that explain this in more thourough
detail - but curretntly I have trouble finding them. Search this newsgroup.
--
Regards,
Diez B. Roggisch
On 2005-03-06, Stewart Midwinter <st************ ***@gmail.com> wrote: I've got an app that creates an object in its main class (it also creates a GUI). My problem is that I need to pass this object, a list, to a dialog that is implemented as a second class. I want to edit the contents of that list and then pass back the results to the first class. So my question is, can a method in one class change an object in another class?
If the answer is no, I suppose I could pass in the list as an argument when I create the second class, then return the contents of the list when I end the methods in that second class.
alternatively, I could make the list a global variable, then it would be available to all classes. I have a nagging feeling though that global variables are to be avoided on general principle. Is this correct?
Here's a simple example app that tries to have one class change the object in another class. It doesn't give the behaviour I want, though.
Depends a bit on who is updating who and which is
created first and which needs references to which.
Maybe like this...
--- #objtest.py
class first:
def __init__(self, a):
self.a = a
print 'a initialized to', self.a
self.updater = second(self)
def update(self, a='aa'):
print 'initially, a is', self.a
self.updater.do _update(a)
print 'afterwards, a is', self.a
class second:
def __init__(self, lst):
self.lst = lst
def do_update(self, a):
self.lst.a = a
if __name__ == '__main__':
lst = first('a')
lst.update()
# or ...
dlg = second(lst)
lst.update('aaa ')
Stewart Midwinter wrote: I've got an app that creates an object in its main class (it also creates a GUI). My problem is that I need to pass this object, a list, to a dialog that is implemented as a second class. I want to edit the contents of that list and then pass back the results to the first class. So my question is, can a method in one class change an object in another class?
Diez and Lee have shown you two ways to do this.
If the answer is no, I suppose I could pass in the list as an argument when I create the second class, then return the contents of the list when I end the methods in that second class.
This is almost what your example does, but you have made a small error. See below.
alternatively, I could make the list a global variable, then it would be available to all classes. I have a nagging feeling though that global variables are to be avoided on general principle. Is this correct?
Yes, it is correct.
Here's a simple example app that tries to have one class change the object in another class. It doesn't give the behaviour I want, though.
--- #objtest.py
class first: def __init__(self): a = 'a' self.a = a print self.a
def update(self): print 'initially, a is', self.a self.a = second(self.a)
The line above is creating an instance of second and assigning it to self.a. What you want to do is
create an instance of second, *call* it, and assign the result to self.a. So you should have
self.a = second(self.a)( self.a)
The self.a parameter passed to second is never used. If you change second.__init__ to
def __init__(self):
pass
then the call in update() will be
self.a = second()(self.a )
Kent print 'afterwards, a is', self.a
class second: def __init__(self, a): pass
def __call__(self, a): a = 'aa' return a
if __name__ == '__main__': app = first() app.update()
thanks, -- Stewart Midwinter st*****@midwint er.ca st************* **@gmail.com
thanks guys. Three good answers, each slightly different, but giving me
good food for thought.
Obviously my example was a trivial one, but I wanted to isolate the
behaviour I'm seeing in my real app. I now have some good ideas for
moving forward!
cheers
S This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Max Ischenko |
last post by:
Hi,
I wrote simple implementation of the "synchronized" methods (a-la Java),
could you please check if it is OK:
def synchronized(method):
"""
Guards method execution, similar to Java's synchronized keyword.
|
by: Andy |
last post by:
Hi
Could someone clarify for me the method parameter passing
concept?
As I understand it, if you pass a variable without
the "ref" syntax then it gets passed as a copy.
If you pass a variable with the "ref" syntax then it gets
passed as a reference to the object and any changes to
|
by: daniel.w.gelder |
last post by:
I wrote a template class that takes a function prototype and lets you
store and call a C-level function, like this:
inline string SampleFunction(int, bool) {..}
functor<string (int, bool)> myFunctor = SampleFunction;
string result = myFunctor(7, true);
Works great thanks to the help from this group. Here's the guts so far
for two-arity:
|
by: JohnR |
last post by:
From reading the documentation, this should be a relatively easy thing. I
have an arraylist of custom class instances which I want to search with
an"indexof" where I'm passing an instance if the class where only the
"searched" property has a value. I expected to get the index into the
arraylist where I could then get the entire class...
|
by: gregory.petrosyan |
last post by:
Hello everybody!
I have little problem:
class A:
def __init__(self, n):
self.data = n
def f(self, x = ????)
print x
All I want is to make self.data the default argument for self.f(). (I
| |
by: zzw8206262001 |
last post by:
Hi,I find a way to make javescript more like c++ or pyhon
There is the sample code:
function Father(self) //every contructor may have "self"
argument
{
self=self?self:this; //every class may have this statement
self.hello = function()
{
|
by: lukasmazur |
last post by:
Hi
I have a problem with using listBox1. I have a two forms form1 and
form2. In form1 are controls listBox1, textBox1 and button witch
creating object of class Form2. In class Form2 I create a pointer to
object of class Form1. I don't known how to use method add(), where
can I find it. From Form1 I can add value like this this->listBox1-...
|
by: VK |
last post by:
<OT>I am finishing TransModal 0.1 so planning to move it from alpha to
beta stage.<OT>
Besides that I am planning to write an introductory to inheritance
schema currently used in Javascript programming. It will not be a
manual of a "proper" way to use OOP inheritance but a compilation so a
description of _all_ OOP paradigms that had been used...
|
by: raylopez99 |
last post by:
I'm posting this fragment from another thread to frame the issue
clearer.
How to pass an object to a function/method call in C# that will
guarantee not to change the object?* In C++, as seen below, you can
use the 'const' keyword in the function / method declaration. But how
to do this in C#?
*for example: "void Foo() const;"
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |