Home > Net >  Python Replacing String with Class?
Python Replacing String with Class?

Time:08-15

I'm new to python so I don't really know a lot in this topic.

I have a function which gets item type, I have three types: A, B and C.

My initial approach was to pass item type as string, for example:

def my_function (item_type):
    if item_type == 'A': ...

But this is a bad approach, what are the alternatives? maybe class, but how to pass it to function

CodePudding user response:

Rather than working with strings, use enums. For example:

from enum import Enum

class Colour(Enum):
    RED = 0
    GREEN = 1
    BLUE = 2

If the colours need to be distinct then just make sure that the values assigned are all different.

Then you might have a function like this:

def func(colour):
    match colour:
        case Colour.RED:
            pass
        case Colour.GREEN:
            pass
        case Colour.BLUE:
            pass

Of course, the enum might be wrapped in some other class but this should get you started

CodePudding user response:

If you are checking instances of classes then you can use isinstance or check using the type function

class A:
   pass

a = A()
print(isinstance(a,A))  # this is the preferred method
print(type(a) == A)

OUTPUT

True
True

If you are checking the classes themselves then you can do a straight comparison.

class A:
    pass

print(A == A)

OUTPUT

True

If you are checking subclasses then you can use issubclass function

class Parent:
    pass

class A(Parent):
    pass

class B(Parent):
    pass

print(issubclass(A, Parent))
print(issubclass(B, Parent))

OUTPUT

True
True


Update from the question in your comment if you want to consolidate classes you could do something like this:

class Color:
    def __init__(self, color):
        self.color = color

red = Color('red')
blue = Color('blue')
green = Color('green')

print(red.color)
print(blue.color)
print(green.color)
print(isinstance(red, Color))
print(isinstance(green, Color))

OUTPUT

'red'
'blue'
'green'
True
True

CodePudding user response:

The good design usually avoids using isinstance() or type() calls. If you need some class-specific logic you better encapsulate it in a class itself. Please refer to: https://refactoring.guru/replace-conditional-with-polymorphism

  • Related