Python Forum
Help me understand this... (Classes and self).
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help me understand this... (Classes and self).
#16
your code
tab_one = tk.Frame(nb) # <-- target actual # #
is making a new frame who's parent is the notebook that has a pointer to it in the variable nb.
this new frame has a pointer to it stored in tab_one which is a local variable to the method build_tab.
when the method build_tab has done all its code, tab_one will be gone leaving no access to the frame.

by changing it to
self.tab_one = tk.Frame(nb) # <-- target actual # #
tab_one becomes a instance variable, that is accessible from both inside the instance(by other methods) and outside the instance(by the object instance).

Example
class MainFrame:
    def __init__(self):
        self.build_nb()
        
    def build_nb(self):
        tab_one = '<local variable>)'
        self.tab_one = '<instance variable>'
        
        print('printed by MainFrame>build_nb:\n'
              f'tab_one = {tab_one}\n'
              f'self.tab_one = {self.tab_one}\n')
        
    def output_tab_one(self):
        print('printed by MainFrame>output_tab_one:\n'
              f'tab_one = tab_one cannot be accessed its forgotten about\n'
              f'self.tab_one = {self.tab_one}\n')
        

main_frame = MainFrame()
main_frame.output_tab_one()
print('printed by instance of MainFrame:\n'
    f'tab_one = tab_one cannot be accessed its forgotten about\n'
    f'self.tab_one = {main_frame.tab_one}')
Output:
printed by MainFrame>build_nb: tab_one = <local variable>) self.tab_one = <instance variable> printed by MainFrame>output_tab_one: tab_one = tab_one cannot be accessed its forgotten about self.tab_one = <instance variable> printed by instance of MainFrame: tab_one = tab_one cannot be accessed its forgotten about self.tab_one = <instance variable>
Reply


Messages In This Thread
RE: Help me understand this... (Classes and self). - by Yoriz - Mar-31-2019, 10:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand classes menator01 7 3,478 Oct-27-2019, 04:26 PM
Last Post: menator01
Question Helping understand classes Miraclefruit 10 6,536 Nov-27-2017, 01:58 PM
Last Post: Windspar
  Using classes? Can I just use classes to structure code? muteboy 5 5,236 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