Normally, to debug a function outside a class I will assign all of its parameters then run & check the function code line by line. (Yes, I know this might not be a professional way!). However, for a function inside a class, it gets error because of the self
For eg, whichever line I run inside this class, it will say:
self.issue_date = issue_date
Traceback (most recent call last):
File "<ipython-input-70-6d3e45750988>", line 1, in <module>
self.issue_date = issue_date
NameError: name 'self' is not defined
So, how to run code inside a class line by line? Or how do you guys debug a function inside a class?
Below is an eg of my class.
class fixed_bond:
def __init__(self, issue_date, settlement_date, first_coupon_date, maturity_date, face_value, df1, df2, coupon_rate, roll, coupon_frequency, day_count_convention):
##################################################################################
#Setting up inital attributes
##################################################################################
self.issue_date = issue_date
self.settlement_date = settlement_date
self.first_coupon_date = first_coupon_date
self.maturity_date = maturity_date
self.face_value = face_value
self.coupon_rate = coupon_rate
if self.roll =='Following':
for i in range(self.number_of_periods):
while cash_flow_dates[i].weekday() < 5:
cash_flow_dates[i]=cash_flow_dates[i] + relativedelta(days = 1)
.......
(end of class eg)
Related
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)
class Player1:
base_HP = 300
def getBHP(self):
return self.base_HP
jogador1 = Player1
jogador1_hp = jogador1.getBHP() #Functions and Class calls must end with brackets.
print(jogador1_hp)
That's the code I'm using to get the player HP and i want to save it at jogador1_hp.
How ever this is what iam getting:
C:\Users\joaol\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/joaol/PycharmProjects/FirstProgram/Main.py
<function Player1.getBHP at 0x02C131E0>
Process finished with exit code 0
Even if i do as below, I'm still getting a blank console.
class Player1:
base_HP = 300
def getBHP(self):
print(self.base_HP)
jogador1 = Player1
jogador1.getBHP
EDIT: I fix it ,i just needed to add "()" when i create the object!
jogador1 = Player1()
jogador1_hp = jogador1.getBHP()
You have to call methods for them to execute.
jogador1_hp = jogador1.getBHP()
You don't instantiate the Player1 class. In your code, jogador1 is just another name for the Player1 class. You should call the class to instantiate it, like: jogador1 = Player1()
If i use jogador1_hp = jogador1.getBHP() i get this :
C:\Users\joaol\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/joaol/PycharmProjects/FirstProgram/Main.py
Traceback (most recent call last):
File "C:/Users/joaol/PycharmProjects/FirstProgram/Main.py", line 19, in <module>
jogador1_hp = jogador1.getBHP()
TypeError: getBHP() missing 1 required positional argument: 'self'
Process finished with exit code 1
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.
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
>>>
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.