u/yiyi164

Can I use 'or' to compare strings?

I'm working on a project to teach myself python and am currently playing around with classes. I've made a class, 'event', and a subclass, 'num_event'. These each have 2 args: outcome and probability. The idea is that these are probabilistic events that I can use for discrete probability experiments like bernoulli trials. I've only defined __init__ in each, and the only difference between the two is that num_event has an extra layer of input data validation to ensure that the outcome is either a float or int. For this validation, I wrote the following function:

def numerical(x)->bool:

| num = (int or float)

| if(type(x) == num):

| | return True

| else:

| | return False

This is pretty simple and works well, which is why I'm so confused that my function 'is_event' is failing:

def is_event(x)->bool:

| events = ('event' or 'num_event')

| if(type(x).__name__ == events):

| | return True

| else:

| | return False

Now, I do understand that I'm going from comparing types to strings, but if I separate the logical test into 2 parts

if(type(x).__name__ == 'event') or (type(x).__name__ == 'num_event'):

It works fine.

Ideally, I'd like to have type(x) return event as a type object like int rather than a string, but that doesn't seem to be the way that user defined classes work.

Regardless, can someone explain why the logical test works for types but not strings? Thanks!

reddit.com
u/yiyi164 — 2 days ago