Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.5 class variables

I'm new to python, and I'm using python 3.5 on Ubuntu. I did some research about this question and i found a lot of answers. What I'm doing looks like what everyone is saying I'm supposed to do, but I'm still receiving errors.

import csv
import sys

Class State():
    started = False

    def waiting(self):
        self.started
        if self.started == False:
            self.started = True
        return

    def buy_in(self, col):
        if self.started == False:
            return
        else:
            print(col)

def read_file(file):
    csv_list = csv.reader(file)
    header = True

    for row in csv_list:
        if header:
            header =  False
            continue

        col = float(row[5])

        if col < 0 :
            State.waiting()
        if col >= 0:
            State.buy_in(col)
    file.close()

def main(filename):
    file = open(filename)
    read_file(file)

def __name__ == '__main__':
    main(sys.argv[1])

I'm just trying to create a pseudo FSM in python, by using a class and methods. I just need to create a global bool. I don't really understand what I'm doing wrong. IF someone doesn't mind giving me some clarity, I would appreciate it. Thanks

To clarify, I'm getting the NameError on the if statement in the buy_in method.

like image 591
John Avatar asked Mar 17 '26 01:03

John


1 Answers

Try:

class State():

    started = False

    def waiting(self):
        if self.started == False:
            self.started = True
        return

    def buy_in(self, col):
        if self.started == False:
            return
        else:
            print(col)

Since started is a class variable you need to use self. when calling it. It is not a global variable so you do not need the global call. Each of the methods inside of the class also needs self as an argument.

like image 52
NendoTaka Avatar answered Mar 21 '26 04:03

NendoTaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!