0

I have a class created in python, with the following structure.

class Bayes():

   def __init__(self,k=1):
     ...

   def train(self,X,y):
     ...

   def classify_prob(self,ejemplo):
     ...

   def classify(self,ejemplo):
     ...

Now, I need to generate a class that gives me an exception (with raise). This exception should give me if I call the classify or classify_prob methods before calling the train method.

The class must have the following structure:

class ClassifyNoTrain(Exception): pass

How could I do this class?. Thank you

1 Answer 1

1

I'm not sure to fully understand your problem, but what about this?

class ClassifyNoTrain(Exception):
    pass


class Bayes():

   def __init__(self,k=1):
       self.train_ok = False

   def train(self,X,y):
       self.train_ok = True

   def classify_prob(self, ejemplo):
       if not self.train_ok:
           raise ClassifyNoTrain()

   def classify(self, ejemplo):
       if not self.train_ok:
           raise ClassifyNoTrain()

b = Bayes()
b.train('X', 'y')  # comment this to raise the exception
b.classify('ejemplo')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I have a question, when I try to execute the code of the form: b = Bayes(), ejemplo = b.train('X', 'y'), b.classify(ejemplo). I have the following error: NameError: name 'ejemplo' is not defined. How could I use the exception for that kind of problem?
Because if you remove the quotes around ejemplo, then this become a variable and not the string "ejemplo" itself. The NameError means that the ejemplo variable is not defined. You have to do something ejemplo = 'blabla' ; b.classify(ejemplo).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.