Sözlük içinden bir IntEnum sınıfını çağırın

Aug 18 2020

Örnek bir IntEnum sınıfım var:

class ShapeMethod(IntEnum):
    NONE = 0
    circle = 1
    square = 2

Bunun __init__başka bir sınıfın işlevi tarafından çağrılması gerekir :

class ExampleClass():
    def __init__(look_at_shapes=None):
        """
        Args:
            look_at_shapes (dict): A dictionary of shape inputs.
        """
        if look_at_shapes:
            self.shape = ShapeMethod.NONE
            if look_at_shapes["colour"]:
                self.colour = look_at_shapes["colour"]

    def do_something_with_shape:
        if self.shape == ShapeMethod.circle:
            print('awesome you got a circle'.)
        elif self.shape == ShapeMethod.square:
            print('squares have 4 sides.')
        else:
            print('nothing to see here.')

nerede, self.shapenitelik olması gerekiyor circle, squareya da NONE.

do_something_with_shapeFonksiyon o zamana kadar çağrılacak olacaktır:

input = {"colour" = blue}
my_object = ExampleClass(look_at_shape=input)
my_object.do_something_with_shape

inputİhtiyaçların yapısı bir sözlük olmalıdır ve colour. Ancak, IntEnumsınıfı bir sözlükten nasıl doğru kullanacağımı bilmiyorum . Örneğin, yazdırmak istersemsquares have 4 sides.

Not: Tüm seçeneklerin ShapeMethod(IntEnum)büyük harfle yazılması gerekiyor mu?


Şimdiye kadar baktığım şey:

Dokümantasyon Python için bir dizi örnek verir; ancak hiçbiri benim durumuma uymuyor.

Yanıtlar

4 bad_coder Aug 18 2020 at 00:51

Kullanmanın bir yolu şudur:

from enum import IntEnum


class ShapeMethod(IntEnum):

    NONE = 0
    circle = 1
    square = 2


class ExampleClass:

    def __init__(self, look_at_shapes=None):
        """
        Args:
            look_at_shapes (dict): A dictionary of shape inputs.
        """
        
        self.shape = None
        self.colour = None

        if look_at_shapes:
            if look_at_shapes[ShapeMethod]:
                self.shape = look_at_shapes[ShapeMethod]

            if look_at_shapes["colour"]:
                self.colour = look_at_shapes["colour"]


    def do_something_with_shape(self):
        if self.shape is ShapeMethod.NONE:
            print('awesome you got a circle.')
        elif self.shape is ShapeMethod.square:
            print('squares have 4 sides.')
        else:
            print('nothing to see here.')


input_var = {
    "colour": 'blue',
    ShapeMethod: ShapeMethod.square
}
my_object = ExampleClass(look_at_shapes=input_var)

my_object.do_something_with_shape()

Yan sorunuzla ilgili olarak:

Not: Tüm seçeneklerin ShapeMethod(IntEnum)büyük harfle yazılması gerekiyor mu?

Bu tamamen size kalmış. Sabit olacağından PEP 8 ile uyumlu olan tümü büyük harf olabilir. Bununla birlikte, birçok kişi yalnızca ilk harfi büyük harf yapmaya karar verir ve bu geçerli bir stil seçimi. En az yaygın olan seçenek, tüm küçük harf kullanmak veya farklı büyük harfleri karıştırmaktır, ancak bunu yapmanızı engelleyen hiçbir şey yoktur. Tam bir referans için bu yanıta bakın.

3 EthanFurman Aug 18 2020 at 00:50
input = {
        "shape": ShapeMethod.square,
        "colour": "blue",
        }


def __init__(look_at_shapes=None):
    """
    Args:
        look_at_shapes (dict): A dictionary of shape inputs.
    """
    look_at_shapes = look_at_shapes or {}
    self.shape = look_at_shapes.get("shape", ShapeMethod.NONE)
    self.colour = look_at_shapes.get("colour")  # None if "colour" doesn't exist

    def do_something_with_shape:
        if self.shape == ShapeMethod.circle:
            print('awesome you got a circle'.)
        elif self.shape == ShapeMethod.square:
            print('squares have 4 sides.')
        else:
            print('nothing to see here.')
2 Jab Aug 18 2020 at 00:23

Enum sınıfındaki temel dizeyi kontrol etmek istediğinizde, self.shape.valueinsead'i kontrol etmeniz gerekir self.shape.

if self.shape.value == 'circle':

Veya

if self.shape == ShapeMethod.circle