Python Forum
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about classes
#1
Hi, I have 2 classes and I want a method which is in the the 2nd class ('class2_method') to be able to access a class variable from the first class. However I need 'class2_method' to be  run from a method in the first class('class1_method').

The following code works ok,  'class1_var1' is changed from "test" to "test2" using 'class2_method'.

class class1():
    def class1_method(self):
        self.class1_var1 = "test"
        self.class2_init = class2()
        self.class2_init.class2_method()
    
class class2():
    def class2_method(self):
        test.class1_var1 = "test2"
        print test.class1_var1

test = class1()
test.class1_method()
However, if I save the two classes as a module file('class_tests).  And then try to do the same thing as before like this:

class class1():
    def class1_method(self):
        self.class1_var1 = "test"
        self.class2_init = class2()
        self.class2_init.class2_method()
    
class class2():
    def class2_method(self):
        test.class1_var1 = "test2"
        print test.class1_var1

import class_tests
reload(class_tests)
test = class_tests.class1()
test.class1_method()
I get this error:

"class2 instance has no attribute 'test' "

Please can anyone tell me what I am doing wrong?  Thanks.
Reply
#2
What is the purpose of saving the file and running a reload?
I don't see any reason for doing that.
What are you using as an IDE? is it's IDLE, if so,
I have seen strange behavior (several years ago) when loading
modules whose name begins with test from IDLE.
Reply
#3
(May-18-2017, 12:04 PM)cybercreature Wrote: Hi, I have 2 classes and I want a method which is in the the 2nd class ('class2_method') to be able to access a class variable from the first class. However I need 'class2_method' to be  run from a method in the first class('class1_method').

There must be a problem with your design if you must do that.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Classes and Objects - question AI_ML_Neophyte 3 2,878 Dec-11-2018, 01:52 PM
Last Post: wavic
  Using classes? Can I just use classes to structure code? muteboy 5 4,978 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020