0

I created this code from a tutorial but have hard time understanding a key concepts: how do 'next' becomes equal to the string "s"? How does self.start refers to that string?

import sys

class DemoClass(object): 

    def __init__(self, start): # executes once!
        self.start = start
        print "_init_"

    def play(self):            # executes once!
        next = self.start
        print "next"

        while True:
            attr = getattr(self, next)  #get attribute of the class
            next = attr()

    def s(self):              # these methods start calling each other once executed
        print "s"
        return 't'

    def t(self):
        print "t"
        i = raw_input(">")
        if i == 's':          # if user input 'i' is equal to 's', call func "s"
            return "s"
        elif i == 'v':
            return "v"
        else:
            exit(0)

    def v(self):
        print "v"
        return 's'  


a = DemoClass("s")
a.play()

4 Answers 4

2

When you initialize the class the first time, you set the entry point to the function spaghetti. play() then kicks off the execution chain based upon what start was. getattr(self, next) will actually get a reference to the class member with that name, and next=attr() will call the member returned by getattr and assign the value returned from that call to next.

As to the methods, when next is 's', s will execute, then next will be 't', which will cause t to be retrieved and executed. t has a raw_input call in it, which means the user can control the next call. If the user imputs 's', t will return 's', if they input 'v', t will return 'v', else the program will exit. v just causes play to loop back to s.

This is kind of a bunch of nonsense logic without any context for why you might want a program structured this way, so I can see why it would be confusing.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your explanation is helped! I took the code from a tutorial, I just wanted to understand how that bit worked.
1

To your first question: getattr returns an attribute of the instance in this case the method s, then you execute it whith attr(), getattr takes an instance and an attribute as a string and returns the attribute object.

Comments

1

I find your code somewhat confusing, but basically what's going on here has to do with a feature of Python classes. Because Python functions are locally scoped, in order to make any modification to the class object itself, every method of a class takes as its first argument the class itself, by convention called 'self'. This object has all of the variables and methods as attributes.

There's also the special __init__ function, which is called when you declare an instance of that class. That also takes self as the first argument, and then any other custom arguments you wish.

As for your question, the following simplified code is how 's' is assigned to next:

class DemoClass(object):

  def __init__(self, the_input):
    # The input on the class declaration is assigned to the 
    #  class attribute 'start'
    self.start = the_input

  def play(self):
    self.next = self.start


  joe = DemoClass('s')
  print joe.start # prints 's'

  print joe.next # raises error, since joe.next hasn't been defined  

  joe.play()
  print joe.next # also prints 's', now that self.next has been defined

Comments

1

how do 'next' becomes equal to the string "s"

Whenever any object method is called, first parameter to the method is automatically set to the object itself. It is commonly referred as self.

When you do a = DemoClass("s"), DemoClass::__init__ is called with parameters self and 's'. Then self.start = start assigns 's' to self.start.

When you call a.play(), the object is sent as the first parameter to play. next = self.start assigns self.start which was assigned to 's' in __init__ to next.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.