Python class function, can't append to list - python

class A:
def __init__(self):
self._list = []
def addItem(self, x):
self._list.append(x)
def main():
while True:
option = int(input("Enter option: "))
if option == 1:
A().addItem("hello")
if option == 2:
print(A()._list)
main()
Sorry haven't been learning from python that long. Can someone explain to me why after option 1 is chosen, the list is still [] after i enter option 2?

Because you are calling different instances. Just introduce a variable here and you would get your desired result. The updated code is
class A:
def __init__(self):
self._list = []
def addItem(self, x):
self._list.append(x)
def main():
a = A()
while True:
option = int(input("Enter option: "))
if option == 1:
a.addItem("hello")
if option == 2:
print(a._list)
main()

Related

Simplifying State Machines (Python)

I want to know why State Machines use an intermediary "State" class at all (between the Concrete States and the Context). From the model below, this could be done with a simple variable.
For example, here's a simplified "containment" style state machine of sorts, which meets the same goal. What am I losing with this model, compared to using a traditional State Machine model?
Also, side question, these child classes are contained because they're indented and part of the parent (Lift) class. What is the difference to this style of inheritance vs un-indenting them and setting them to something like this: class FloorOne(Lift):
class Lift:
def __init__(self):
self.current_state = Lift.FloorOne(self)
def show_input_error(self):
print("Incorrect input")
class FloorOne:
def __init__(self, lift):
self.lift = lift
print("You are on Floor One")
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num == 2:
self.lift.current_state = Lift.FloorTwo(self.lift)
elif num == 3:
self.lift.current_state = Lift.FloorThree(self.lift)
else:
self.lift.show_input_error()
class FloorTwo:
def __init__(self, lift):
self.lift = lift
print("You are on Floor Two")
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num == 1:
self.lift.current_state = Lift.FloorOne(self.lift)
elif num == 3:
self.lift.current_state = Lift.FloorThree(self.lift)
else:
self.lift.show_input_error()
class FloorThree:
def __init__(self, lift):
self.lift = lift
print("You are on Floor Three")
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num == 1:
self.lift.current_state = Lift.FloorOne(self.lift)
elif num == 2:
self.lift.current_state = Lift.FloorTwo(self.lift)
else:
self.lift.show_input_error()
lift = Lift()
while True:
goto = input("What floor would you like to go to?")
lift.current_state.button_press(int(goto))
If you define all the floor classes as subclasses from a common class State, you gain:
It is clear, from the code, which is the common interface of the concrete states. Even you can enforce an interface adding abstract methods which have to be overriden in the concrete classes in order to be able to be instantiated
You have to code less, because you can define the methods which are equal for all states once, in the State class. For example the button_press method.
Makes code easier to change.
Look at this code:
class Lift:
def __init__(self):
self.current_state = Lift.FloorOne(self)
def show_input_error(self):
print("Incorrect input")
class State:
def __init__(self, lift):
self.lift = lift
print(f'You are on Floor {self.floor_name}')
def button_press(self, num):
self.transition(num)
def transition(self, num):
if num != self.floor_num and num in [1,2,3]:
self.lift.current_state = [Lift.FloorOne,
Lift.FloorTwo,
Lift.FloorThree][num - 1](self.lift)
else:
self.lift.show_input_error()
class FloorOne(State):
floor_name = 'One'
floor_num = 1
class FloorTwo(State):
floor_name = 'Two'
floor_num = 2
class FloorThree(State):
floor_name = 'Three'
floor_num = 3
lift = Lift()
while True:
goto = input("What floor would you like to go to?")
lift.current_state.button_press(int(goto))
Now it is easier to add a floor.
If you want you can override any of the methods in a subclass for a different behavior:
class BrokenLift(State):
def transition(self, num):
print('broken lift!')

(Python) Why my inheritence does not work?

class Bin():
def __init__(self):
self.bin = {}
def add_to_bin(self, medId , medName):
self.bin[medId] = medName
def remove_by_id(self, id):
self.bin.pop(id)
def clean_bin(self):
self.bin.clear()
def check_ids(self):
list(self.bin.keys())
def check_names(self):
list(self.bin.values())
def check_inventory(self):
list(self.bin.items())
if __name__ == "__main__":
bin1 = Bin()
bin1.add_to_bin(100, "advil")
bin1.add_to_bin(200, "tylenol")
bin1.add_to_bin(300, "pepto-bismol")
bin1.check_inventory()
What am I doing wrong? I am so confused.
I am trying to create a medical storage system with multiple dictionaries. Whenever I try to run the code, it does not return anything.
Firstly there is no inheritance in your code. It is just a class and object code. Second you need to return data from your methods.
class Bin():
def __init__(self):
self.bin = {}
def add_to_bin(self, medId , medName):
self.bin[medId] = medName
def remove_by_id(self, id):
self.bin.pop(id)
def clean_bin(self):
self.bin.clear()
def check_ids(self):
return list(self.bin.keys())
def check_names(self):
return list(self.bin.values())
def check_inventory(self):
return list(self.bin.items())
if __name__ == "__main__":
bin1 = Bin()
bin1.add_to_bin(100, "advil")
bin1.add_to_bin(200, "tylenol")
bin1.add_to_bin(300, "pepto-bismol")
inventory = bin1.check_inventory()
print(inventory)
ids = bin1.check_ids()
print(ids)
names = bin1.check_names()
print(names)

How to replace an integer with a different class when it is assigned

I have a class called newInteger, and a variable called num, but I would like num to be a newInteger() instead of an int(). Code below.
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
I want the line num = 10 to act as if it is num = newInteger(10). Thanks to anyone who can help me with this.
You can run a small thread parallel to your main program that replaces all created integers to newInteger:
import threading
import time
class newInteger(int):
def __init__(self, value):
self.value = value
def __str__(self):
return "newInteger " + str(self.value)
def replace_int():
while True:
g = list(globals().items())
for n, v in g:
if type(v) == int:
globals()[n] = newInteger(v)
threading.Thread(target=replace_int, daemon=True).start()
num = 10
time.sleep(1)
print(num)
But this is unpythonic and will be realy hard to debug. You should just use a explicit conversion like #johnashu proposed
I am not sure if this is what you mean but if youassign the class to a variabl. then it will be an instance of that class..
example:
class newInteger(int):
def __init__(self, value):
self.value = value
num = 10
if num == 10:
num = newInteger(10)
prints:
hello

Python - Classes - Self Not Defined

Below I'm attempting to make a simple Keygen as a first project. Somewhere I'm getting the error the Self has not been defined.
I'm guessing it's probably something easy
import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def KeyGen4(self):
while self.counter != self.length:
a = random.choice(self.Letters)
print a #test
r = (random.randint(0,1))
print r #test
if r == True:
a = a.upper()
else:
pass
self.key.append(a)
self.counter += 1
s = ''
self.key = s.join(key)
print self.key
return self.key
def start(self):
selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >')
if selection == 'K' or 'k':
length = 4
keyGen4(self)
elif selection == 'N' or 'n':
KeyGenN(self)
elif selection == 'C' or 'c':
length = int(raw_input("Key Length: "))
#KeyGen4(self) # Change later after creating method with more options
start(self)
Your indention is wrong, but I assume this is only a copy-pasting issue.
That start(self) at the bottom doesn't make sense,
and indeed self is not defined there. You should create an instance of the class, and then call its start method:
KeyGenerator().start()
# or
key_gen = KeyGenerator()
key_gen.start()
You have two problems:
you miss indentation on every class-function
you must create an object of the class before you can call any of its functions
Your class should look like this
import random
class KeyGenerator():
def __init__(self):
length = 0
counter = 0
key = []
Letters = ['a','b','c','d','e']
def KeyGen4(self):
while self.counter != self.length:
a = random.choice(self.Letters)
print a #test
r = (random.randint(0,1))
print r #test
if r == True:
a = a.upper()
else:
pass
self.key.append(a)
self.counter += 1
s = ''
self.key = s.join(key)
print self.key
return self.key
def start(self):
selection = raw_input('[K]eygen4, [C]ustom length Keygen or [N]umbers? >')
if selection == 'K' or 'k':
length = 4
self.keyGen4()
elif selection == 'N' or 'n':
self.KeyGenN()
elif selection == 'C' or 'c':
length = int(raw_input("Key Length: "))
#KeyGen4(self) # Change later after creating method with more options
#now make an instance of your class
my_key_gen = KeyGenerator()
my_key_gen.start()
Please note that when calling class functions inside the class, you need to use self.FUNCNAME. All class functions should take "self" as argument. If that is their only argument then you simply call them with self.func(). If they take arguments you still ommit the self, as self.func(arg1, arg2)

Understanding Stacks and Queues in python

So i was given this question. Consider the Stack and the Queue class with standard set of operations. Using the Stack and Queue class, what items are contained in them just before the mysteryFunction is called AND just after the mysteryFunction is called?
Here is the code:
def mysteryFunction(s, q):
q.enqueue('csc148')
q.enqueue(True)
q.enqueue(q.front())
q.enqueue('abstract data type')
for i in range(q.size()):
s.push(q.dequeue())
while not s.is_empty():
q.enqueue(s.pop())
if __name__ == '__main__':
s=Stack()
q=Queue()
#About to call mysteryFunction
#What are contents of s and q at this point?
mysteryFunction(s, q)
#mysteryFunction has been called.
#What are contents of s and q at this point?
I'm having trouble understanding object oriented programming as i'm new to this topic. Is there any link that breaks down Stacks and Queues and what they do?
In general, stacks are LIFO and queues are FIFO.
In Python, you can use the collections module to experiment with stacks and queues:
>>> from collections import deque
>>> stack = deque()
>>> stack.append(10)
>>> stack.append(20)
>>> stack.append(30)
>>> stack
deque([10, 20, 30])
>>> stack.pop() # LIFO
30
>>> stack.pop()
20
>>>
>>> queue = deque()
>>> queue.append(10)
>>> queue.append(20)
>>> queue.append(30)
>>> queue
deque([10, 20, 30])
>>> queue.popleft() # FIFO
10
>>> queue.popleft()
20
See following links for more information:
Stack
Queue
Visually these two data structures can be seen in a following way:
Stack:
Description:
There are variations of this data structure. However, in simple terms - as one can observe in the image provided, when you add to this data structure you place on top of what is already there and when you remove you also take from the top. You can view it as a stack of books which you go through one by one starting from the top and all the way down.
Queue
Description:
There are also variations on this particular data structure, however in simple terms - as you can see in the image provided, when you add to this data structure the new element goes in the begining and when you remove its the last element from the list which is being removed. You can imagine it as a queue you got in a shop where you stand behind a lot of people waiting for your turn to come to the counter to pay for your items.
To test this line by line, here are implementations of the classes (wrappers around deque) that are used in the task:
from collections import deque
class Queue(deque):
enqueue = deque.append
dequeue = deque.popleft
def front(self):
return self[-1]
def size(self):
return len(self)
class Stack(deque):
push = deque.append
def is_empty(self):
return not self
STACK #LIFO
class stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop (self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return (len(self.items))
s = stack()
print (s.isEmpty())
>> True
s.push(1)
s.push('3')
s.peek()
>>'3'
s.size()
>> 2
Queue #FIFO
class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items==[]
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return (len(self.items))
q = Queue()
q.isEmpty()
>>True
q.enqueue(1)
q.enqueue(2)
q.dequeue()
>>1
The first code explains about the stack , we need to create a list and while pushing the element use append and fill the list , similar to what we have in array stack. While pop , pop out the end from where you pushed it.
class Stack:
def __init__(self):
self.stack = []
def push_element(self,dataval):
self.stack.append(dataval)
return self.stack
def pop_element(self):
if len(self.stack) ==0:
print("Stack is empty")
else:
self.stack.pop()
return self.stack
def peek_element(self):
return self.stack[0]
class Queue:
def __init__(self):
self.stack = []
def push_ele(self,data):
self.stack.append(data)
def pop_ele(self):
self.stack.pop(0)
def display(self):
print(self.stack)
class stack:
def __init__(self,n): #constructor
self.no = n # size of stack
self.Stack = [] # list for store stack items
self.top = -1
def push(self): # push method
if self.top == self.no - 1: # check full condition
print("Stack Overflow.....")
else:
n = int(input("enter an element :: "))
self.Stack.append(n) # in list add stack items use of append method
self.top += 1. # increment top by 1
def pop(self): # pop method
if self.top == -1: # check empty condition
print("Stack Underflow....")
else:
self.Stack.pop(). # delete item from top of stack using pop method
self.top -= 1 # decrement top by 1
def peep(self): #peep method
print(self.top,"\t",self.Stack[-1]) #display top item
def disp (self): # display method
if self.top == -1: # check empty condition
print("Stack Underflow....")
else:
print("TOP \tELEMENT")
for i in range(self.top,-1,-1): # print items and top
print(i," \t",self.Stack[i])
n = int(input("Enter Size :: ")) # size of stack
stk = stack(n) # object and pass n as size
while(True): # loop for choice as a switch case
print(" 1: PUSH ")
print(" 2: POP ")
print(" 3: PEEP ")
print(" 4: PRINT ")
print(" 5: EXIT ")
option = int(input("enter your choice :: "))
if option == 1:
stk.push()
elif option == 2:
stk.pop()
elif option == 3:
stk.peep()
elif option == 4:
stk.disp()
elif option == 5:
print("you are exit!!!!!")
break
else:
print("Incorrect option")

Categories