Python 3.5 class variables - python-3.x

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.

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.

Related

Nested function in Python class

i have a little "basic understanding" Python problem.
So let me explain my problem.
At first a very simple code snippet.
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self.__sentence
def revert_sentence(self):
return self.__sentence[::-1]
if __name__ == '__main__':
print(Revert("Stackoverflow").get_sentence())
print(Revert("Stackoverflow").revert_sentence())
So this show normal function calling of python functions.
But how can i transform this code so i can call the revert function like this:
print(Revert("Stackoverflow").get_sentence().revert_sentence())
Maybe I'm miss the forest through the trees. But I didn't get it how to do this.
I already tried to solve the problem with innermethods but this didn't work for me
...
def get_sentence(self):
def revert_sentence():
self.revert_sentence()
return self.__sentence
...
Many thanks in advance
Implement __str__ to return the actual string. Then in the existing methods, return the object. This way you can chain. But when print is applied to it, that __str__ method will kick in:
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self
def revert_sentence(self):
return Revert(self.__sentence[::-1])
# Some more such methods ...
def upper(self):
return Revert(self.__sentence.upper())
def first(self, count):
return Revert(self.__sentence[:count])
def dotted(self):
return Revert(".".join(self.__sentence))
# For getting a string
def __str__(self):
return self.__sentence
print(Revert("Stackoverflow").get_sentence().revert_sentence())
print(Revert("Stackoverflow")
.revert_sentence()
.first(8)
.upper()
.revert_sentence()
.first(4)
.dotted()) # "O.V.E.R"
Note that now the .get_sentence() method is not really doing much, and you can always strip it from a chain.
Here You go:
class Revert:
__sentence = ""
def __init__(self, sentence: str):
self.__sentence = sentence
def get_sentence(self):
return self.__sentence
def revert_sentence(self):
# It's important to know that you are making changes in the same instance of the object
self.__sentence = self.__sentence[::-1]
return self
def pseudo_revert(self):
# Return a new object with reverted string, but this instance still has original string intact.
return Revert(self.__sentence[::-1])
if __name__ == '__main__':
r1 = Revert("Stackoverflow")
r2 = Revert("Stackoverflow")
print(r1.get_sentence()) # Stackoverflow
print(r1.revert_sentence().get_sentence()) # wolfrevokcatS
print(r1.get_sentence()) # wolfrevokcatS
print(r2.get_sentence()) # Stackoverflow
print(r2.pseudo_revert().get_sentence()) # wolfrevokcatS
print(r2.get_sentence()) # Stackoverflow
Hope this helps you understand the object, instance of an object, and method of object distinctly.

Is it possible to make a class which lets you stack enum Flags?

I'd like to use named constants whereever possible instead of providing literal values or longish function signatures with a lot of boolean args.
Therefore i like pythons enum.Flag or enum.Enum.
More precisely, I would like to pass an argument to a function which holds a bit combination of enum.Flags. And i would like to avoid writing module.TheFlags.flagX for every set flag I would like to pass to the function. The flags should replace the boolean args.
I came up with following code:
import enum
class AvailableFlags(enum.Flag):
flag1 = enum.auto()
flag2 = enum.auto()
class FuncFlags:
def __init__(self):
self._flags = AvailableFlags(0)
#property
def flag1(self):
self._flags |= AvailableFlags.flag1
return self
#property
def flag2(self):
self._flags |= AvailableFlags.flag2
return self
def __str__(self):
return str(self._flags.value)
def func(setup_flags: FuncFlags):
print(setup_flags)
if __name__ == "__main__":
func(FuncFlags().flag1)
func(FuncFlags().flag2)
func(FuncFlags().flag1.flag2)
func(FuncFlags())
It creates instances of FuncFlags and then mis-uses the properties to set single flags returning the changed object itself.
However, one would expect that the property does NOT change object state.
Therefore, this is obviously not a clean solution despite that it works, though.
So, my question is, how this can be implemented in a clean, reusable way?
I'm not really clear on what you are trying to accomplish, but perhaps this helps?
import enum
class AvailableFlags(enum.Flag):
flag1 = enum.auto()
flag2 = enum.auto()
flag1, flag2 = AvailableFlag
def func(setup_flags: AvailableFlags):
print(setup_flags)
if __name__ == "__main__":
func(flag1)
func(flag2)
func(flag1|flag2)
func()
Meanwhile, I found an answer by adding another level of indirection.
I want to share it here if it is of interest for someone else.
Object state is maintained as every invokation of a flag creates a new instance from the current instance by setting an additional flag.
If we attempt to access an undefined flag an exception is raised (not shown).
import enum
class AvailableFlags(enum.Flag):
flag1 = enum.auto()
flag2 = enum.auto()
class FlagHelper:
def __init__(self, cls, value = 0):
self._cls = cls
self._flags = self._cls(value)
def __getattr__(self, item):
if item in self._cls.__members__:
return self.__class__(self._flags | getattr(self._cls, item))
getattr(self._cls, item) # Let attribute error pass through
def __str__(self):
return str(self._flags.value)
class FuncFlags(FlagHelper):
def __init__(self, value = 0):
super().__init__(AvailableFlags, value)
def func(setup_flags: FuncFlags):
print(setup_flags)
if __name__ == "__main__":
ff = FuncFlags()
func(ff.flag1)
func(ff.flag2)
func(ff.flag1.flag2)
func(ff)
Output:
1
2
3
0

Error with exit code -1073740791 (0xC0000409) in python

so the program that I am trying to make accepts only a valid month and year between 2018-2050 but pycharm crushes with the message "Process finished with exit code -1073740791 (0xC0000409)" and I know in which line it does that, but I dont know how to fix it, here is the code I am using and the error appers in the last elif when ok is clicked. I have tried reinstalling python and pycharm, as suggested in other posts but nothing happens.
import sys
from PyQt5.QtWidgets import (QVBoxLayout,QHBoxLayout,QPushButton,
QLineEdit,QApplication,QLabel,QCheckBox,QWidget)
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def accepted(month, year):
conf = True
try:
int(month)
int(year)
except ValueError:
conf = False
if conf:
if (int(month) > 12 or int(month) < 1) or (int(year) < 2019 or
int(year) > 2050):
conf = False
return conf
def init_ui(self):
self.btn1=QPushButton('OK')
self.btn2=QPushButton('Clear')
self.btn3=QPushButton('Cancel')
self.txt1=QLabel('Month input')
self.txt2=QLabel('Year Input')
self.b1=QLineEdit()
self.b2=QLineEdit()
h_box1: QHBoxLayout=QHBoxLayout()
h_box1.addWidget(self.txt1)
h_box1.addWidget(self.b1)
h_box2 = QHBoxLayout()
h_box2.addWidget(self.txt2)
h_box2.addWidget(self.b2)
h_box3=QHBoxLayout()
h_box3.addWidget(self.btn1)
h_box3.addWidget(self.btn2)
h_box3.addWidget(self.btn3)
layout=QVBoxLayout()
layout.addLayout(h_box1)
layout.addLayout(h_box2)
layout.addLayout(h_box3)
self.setLayout(layout)
self.setWindowTitle('Calendar Manager')
self.show()
self.btn1.clicked.connect(self.buttons)
self.btn2.clicked.connect(self.buttons)
self.btn3.clicked.connect(self.buttons)
def buttons(self):
clicked=self.sender()
if clicked.text() == 'Clear':
self.b1.clear()
self.b2.clear()
elif clicked.text() == 'Cancel':
sys.exit()
elif clicked.text() == 'OK':
if not accepted(self.b1.text(),self.b2.text()):
self.b1.clear()
self.b2.clear()
else:
pass
app=QApplication(sys.argv)
a_window=Window()
sys.exit(app.exec_())
So the problem is the self in two instances, first as an argument in def accepted and secondly the self.accepted when I call it.
As you mentioned, the problem is with function accepted. If you intended it to be a class method, it should have been defined as:
def accepted(self, month, year):
....
You don't use 'self' in the method, so it could be turned into a static method:
#staticmethod
def accepted(month, year):
....

How to fix "None" answer and Take inputs as arguments?

I'm giving mettl exam and the question was for solving the parenthesis are matching or not.But all I'm getting as result is NONE.
I'm not sure how to take the input as argument, please help out:
I've tried changing, it is taking the input if I provide a hard coded one.
'''
# these are the metll instructions
class UserMainCode(object):
#classmethod
def areParenthesisBalanced(cls, input1):
'''
input1 : string
Expected return type : string
'''
# Read only region end
# Write code here
pass
'''
# this is the code I tried
class Stack():
def __init__(self):
self.items=[]
def push(self,item):
self.items.append(item)
def is_empty(self):
return self.items == []
def pop(self):
return self.items.pop()
def show_me(self):
return self.items
def peek(self):
if not self.is_empty():
return self.items[-1]
input1=[]
def areParenthesisBalanced(input1):
s=Stack()
is_balanced=True
index=0
def is_match(p1,p2):
if p1=="(" and p2==")":
return True
elif p1=="[" and p2=="]":
return True
elif p1=="{" and p2=="}":
return True
else:
return False
while index< len(input1) and is_balanced:
paren=input1[index]
if paren in"({[":
s.push(paren)
else:
if s.is_empty():
is_balanced=False
else:
top = s.pop()
if not is_match(top,paren):
is_balanced=False
index+=1
if s.is_empty() and is_balanced:
return True
else:
return False
print (areParenthesisBalanced(input1))
I was hoping to atleast get a normal True. I'm not sure how to proceed

Mocking a while statment Python

Im pretty new at mocking in Python. I searched pretty deeply for any post that answered this question, but i failed to do so. I want to mock a function that is called within a while statement. Is there anyway to do this?
def some_function(self, some_param):
some_counter = 0
while self.func_i_want_to_mock(mock_param, mock_param2) is False:
some_counter += 1
return some_counter
I want to mock a function that is called within a while statement
Define a side effect function if you want to play with the parameters
def func_tbm_side_effect(first, second):
return 'whatever'
Now with the testing
import unittest
import mock
import ClassWithSomeFunc
class TestClassWithSomeFunc(unittest.TestCase):
def test_some_function(self):
with mock.patch.object(ClassWithSomeFunc, 'some_function') as mocked_sf:
mocked_sf.side_effect = func_tbm_side_effect
item = ClassWithSomeFunc()
value = item.some_function('parameter')
self.assertEqual(value, 'endless loop')
def some_function(self, some_param):
some_counter = 0
while self.func_i_want_to_mock(mock_param, mock_param) is False:
some_counter += 1
return some_counter
def func_i_want_to_mock(mock_param, mock_param):
if mock_param1 == x and mock_param2 == y:
return True
elif """ ... all cases"""

Resources