Create a class within a class and instance in outer scope? - python

I am trying to implement consumer - producer problem in Python… The one question I have is whether I can create a class within a class and create an object of it in the outer scope as in the code below:
class Main(threading.Thread):
def __init__(self):
processNumber = 0
queue_size=5
self.mutexProducer=thread.allocate_lock()#mutex variablaes
self.mutexConsumer=thread.allocate_lock()
self.mutexTeller=thread.allocate_lock()
self.queue=Queue.Queue(maxsize=queue_size)
self.producer=Producer(processNumber,random.random())
class Producer(threading.Thread):
def __int__(self,ProducerID,serviceTime):
self.id=ProcucerID
self.serviceTime=serviceTime
def run(self):
#mutexProducer.acquire()
#Entering Critical section
print queue.qsize()
if queue.full():
sleep(random.random())
else:
print "Customer %d Enters the Queue" %(self.id)
app=Main()
I am getting the following error:
Traceback (most recent call last): File "/Users/sohil/Desktop/sync.py", line 55, in <module>
app=Main() File "/Users/sohil/Desktop/sync.py", line 36, in __init__
self.producer=Producer(processNumber,random.random()) NameError: global name 'Producer' is not defined

Change the order.
class Producer(threading.Thread):
def __int__(self,ProducerID,serviceTime):
self.id=ProcucerID
self.serviceTime=serviceTime
def run(self):
#mutexProducer.acquire()
#Entering Critical section
print queue.qsize()
if queue.full():
sleep(random.random())
else:
print "Customer %d Enters the Queue" %(self.id)
class Main(threading.Thread):
def __init__(self):
processNumber = 0
queue_size=5
self.mutexProducer=thread.allocate_lock()#mutex variablaes
self.mutexConsumer=thread.allocate_lock()
self.mutexTeller=thread.allocate_lock()
self.queue=Queue.Queue(maxsize=queue_size)
self.producer=Producer(processNumber,random.random())
Python is an interpreted language which executes from top to bottom so any dependencies must be declared at the top.

Related

Trouble Creating Instance of Class

I have the code below, but I am getting an error when I try to create an instance of the class.
class Flight():
def __init__(self, capacity):
self.capacity = capacity
self.passengers = []
def add_passenger(self, name):
if not self.open_seats():
return False
self.passengers.append(name)
return True
def open_seats(self):
return self.capacity - len(self.passengers)
f = Flight(3)
people = ["Aicel", "Angela", "Randy", "Monina"]
for person in people:
success = flight.add_passengers(person)
if success:
print(f"Added {person} to flight successfully")
else:
print(f"No available seats for {person}")
This the error message:
Traceback (most recent call last):
File classflight.py Line 19, in <module>
success = flight.add_passenger(person)
NameError: name 'flight' is not defined
The error message tells you: name 'flight' is not defined.
If you look closer at the line in question from the error message (success = flight.add_passenger(person)) and the rest of your code, you see that the Flight instance that you created is not named flight but f. So to make your code work,
either change f = Flight(3) to flight = Flight(3)
or change success = flight.add_passenger(person) to success = f.add_passenger(person)

module import class function [duplicate]

This question already has answers here:
Python - Why is this class variable not defined in the method?
(3 answers)
Closed 4 years ago.
Hello I ve a stupid pb that stucks me, I don t understand why the str argument in not taken into account :
Here is tst.py:
class CurrenciPair():
def __init__(self, market_pair):
self.market_pair = market_pair
def displayCount(self):
histo = market_pair
print(market_pair)
Outside the class:
def reco(market_pair):
print(market_pair)
emp = CurrenciPair(market_pair)
emp.displayCount()
Here is test.py that import the previous file:
import tst as tt
market = 'TEST'
tt.reco(market)
Here is the result:
>>python test.py
TEST
Traceback (most recent call last):
File "test.py", line 5, in <module>
tt.reco(market)
File "C:\Users\or2\Downloads\crypto\API\python_bot_2\tst.py", line 19, in reco
emp.displayCount()
File "C:\Users\or2\Downloads\crypto\API\python_bot_2\tst.py", line 10, in displayCount
histo = market_pair
NameError: name 'market_pair' is not defined
In Python, you must use self to access members of an object. So, use self.market_pair to access the attribute:
class CurrenciPair():
def __init__(self, market_pair):
self.market_pair = market_pair
def displayCount(self):
histo = self.market_pair
print(self.market_pair)
Precision about self
You could also replace self with anything, it's a convention:
class CurrenciPair():
def __init__(anything, market_pair):
anything.market_pair = market_pair
def displayCount(anything):
print(anything.market_pair)

NameError on initialization of class instance

I have been playing around with scripts for a couple of weeks and have not had any issues, but I am now trying to create a class and am running into problems.
I don't fully understand it myself but I am getting this error NameError: global name 'instance_status_check' is not defined when I try to create an instance of the following class.
I am fully aware the class isn't doing much at this time but I can't move on until I resolve the problem. Can someone explain what I am doing wrong?
import sys
import boto
import boto.ec2
class Monitor:
def __init__(self,conn,identifier):
self.connection = conn
self.identifier = identifier
self.dispatcher ={'1': instance_status_check}
def user_menu():
for i, value in self.dispatcher.itertems():
print "Please press {i} for {value}".format(i,value)
def instance_status_check():
pass
You are missing the self parameter from both methods and it is iteritems not itertems:
class Monitor: # upper case for class names
def __init__(self,conn,identifier):
self.connection = conn
self.identifier = identifier
self.dispatcher ={'1': self.instance_status_check} # call self.instance_status_check()
def user_menu(self): # self here
for i, value in self.dispatcher.iteritems():
print("Please press {i} for {value}".format(i,value))
def instance_status_check(self): # self here
return "In status method"
m = Monitor(3,4)
print(m.dispatcher["1"]())
In status method
I suggest you have a look at the classes tutorial from the docs
You have this error because you have defined instance_status_check after you are already using it.
Move the declaration above the class:
def instance_status_check():
pass
class monitor:
def __init__(self,conn,identifier):
self.connection = conn
self.identifier = identifier
self.dispatcher ={'1': instance_status_check}
def user_menu(self):
for i, value in self.dispatcher.itertems():
print "Please press {i} for {value}".format(i,value)
Also, this will not print Please press 1 for instance_status_check it will print something like Please press 1 for <function instance_status_check at 0xsomething>

Python: Class: Calling a function in the same class

Good day..
I'm kinda struggling in my learning process in Class. Let me show my code, and what is happening.
from random import randint
print "Start"
class Simulation (object):
def __init__(self):
self.bankroll= 5000
self.bet=0
self.betLevel= 0
self.betList=[5,5,5,10,15,25,40,65,100]
self.wlist=[]
self.my_file=open("output.txt","w")
self.winningNumber=0
self.myNumber=[4,5,7,8]
self.testCase=1
self.my_file.write("Test case Bet Number Outcome Bankroll")
def gamble(self):
self.bet=self.betList[self.betLevel]
if self.bankroll < 1000 :
self.bet= 5
self.winningNumber= randint(0,36)
if self.winningNumber in self.myNumber:
win()
else:
lose()
def win(self):
self.bankroll +=(17*self.bet)
self.wlist= [self.testCase,self.bet,self.winningNumber,"WIN",self.bankroll]
self.betLevel=0
write()
def lose(self):
self.bankroll -=self.bet
self.wlist= [self.testCase,self.bet,self.winningNumber,"LOSE",self.bankroll]
self.betLevel +=1
write()
def write(self):
self.my_file.write(" ".join(self.wlist))
def startSimulation(self):
for i in range (100):
gamble()
closeFile()
def closeFile(self):
self.my_file.close()
mySimulation= Simulation()
mySimulation.startSimulation()
print "DONE"
So in this code, I'm trying to simulating a roulette game, using a weird betting system. It works like Martingale, but instead of doubling, I follows Fibonacci sequence.
So my problem is that I got this error:
Traceback (most recent call last):
File "D:\Roulette simulation\python 3.py", line 44, in <module>
mySimulation.startSimulation()
File "D:\Roulette simulation\python 3.py", line 38, in startSimulation
gamble()
NameError: global name 'gamble' is not defined
My question. Why? I mean, I'm calling a function in the same class? Why I got the global error?
Within a method, you have self as a reference to your instance. You can access methods on that instance through that reference:
self.gamble()
There is no global gamble function here; the method is part of the Simulation class. This applies to all methods; you'll have to call closeFile, lose, win and write on self as well, for example.
Try running
self.gamble()
in class functions,self means class itself(someone use 'cls' instead of 'self'), so self.gamble means gamble function of this class
if you want to run a function in the position of class attribution
>>> class P:
name = 'name'
def getage(self):
return 18
age = property(getage)
>>> p = P()
>>> p.age
18
>>>

Class Attribute is clearly there, but python cant find it

Why am i getting this attribute error?
class GameState(object):
"""Keeps track game state variables"""
def __init__(self, convo_flag=0, characters_talked_to=0, convo_log=(None)):
self.convo_flag = convo_flag
self.characters_talked_to = characters_talked_to
self.convo_log = convo_log
def welcome_screen():
global LAST_NAME
global BULLY
global DAY
raw_input(messages.WELCOME)
LAST_NAME = raw_input(messages.LAST_NAME)
BULLY = characters.random_character(cclass='Camper', gender='m')
print 'Your name is Pickett %s' % LAST_NAME
messages.print_messages([
messages.EXPLANATION,
messages.BUS_LOADING,
messages.CRACK,
messages.GAME_KID_LOST])
return week_one(DAY)
def week_one(day):
if day == 1:
messages.print_messages(messages.WEEK_ONE[day])
campers = characters.random_character_sample(cclass='Camper', count=5)
people_outside_theater = campers + [characters.TROID]
while GameState.characters_talked_to != 3:
I dont get why im getting this attribute error, i totally declared it in that constructor, is there something i am missing were i need to declare it outside the constructor? This is really racking my brain.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pickett.py", line 44, in welcome_screen
return week_one(DAY)
File "pickett.py", line 52, in week_one
while GameState.characters_talked_to != 3:
AttributeError: type object 'GameState' has no attribute 'characters_talked_to'
You need to create an instance in order you use your class like this:
gameState = GameState()
while gameState.characters_talked_to != 3:
In your code you were trying to access class-level attribute which is not defined in your class.
Your __init__ function sets characters_talked_to on self, which is an instance of GameState.
You did not set it on GameState, which is a class.
Neither did you create any instances of GameState, so in any case __init__ is never called by your program.

Categories