IT Share you

Python 클래스 메서드의 사용 사례의 예는 무엇입니까?

shareyou 2020. 12. 11. 20:53
반응형

Python 클래스 메서드의 사용 사례의 예는 무엇입니까?


파이썬에서 클래스 메서드는 무엇입니까?를 읽었습니다 . 그러나 그 게시물의 예는 복잡합니다. Python의 클래스 메서드에 대한 특정 사용 사례에 대한 명확하고 간단하며 베어 본 예제를 찾고 있습니다.

Python 클래스 메서드가 작업에 적합한 도구가 될 수있는 작고 구체적인 사용 사례의 이름을 지정할 수 있습니까?


초기화를위한 도우미 메서드 :

class MyStream(object):

    @classmethod
    def from_file(cls, filepath, ignore_comments=False):    
        with open(filepath, 'r') as fileobj:
            for obj in cls(fileobj, ignore_comments):
                yield obj

    @classmethod
    def from_socket(cls, socket, ignore_comments=False):
        raise NotImplemented # Placeholder until implemented

    def __init__(self, iterable, ignore_comments=False):
       ...

그럼 __new__꽤 중요한 classmethod입니다. 일반적으로 인스턴스가 발생하는 곳입니다.

그래서 dict()전화 dict.__new__물론,하지만 때로는 classmethod 인 dicts을하는 또 다른 편리한 방법이dict.fromkeys()

예.

>>> dict.fromkeys("12345")
{'1': None, '3': None, '2': None, '5': None, '4': None}

이름이 지정된 생성자 메서드와 같은 것입니까?

class UniqueIdentifier(object):

    value = 0

    def __init__(self, name):
        self.name = name

    @classmethod
    def produce(cls):
        instance = cls(cls.value)
        cls.value += 1
        return instance

class FunkyUniqueIdentifier(UniqueIdentifier):

    @classmethod
    def produce(cls):
        instance = super(FunkyUniqueIdentifier, cls).produce()
        instance.name = "Funky %s" % instance.name
        return instance

용법:

>>> x = UniqueIdentifier.produce()
>>> y = FunkyUniqueIdentifier.produce()
>>> x.name
0
>>> y.name
Funky 1

@classmethod코드를 사용하기 위해 클래스의 인스턴스가 필요하지 않은 경우 전역 함수 생성을 방지하기 위해 코드를 클래스와 연결하는 데 가장 자주 사용 합니다.

예를 들어, 어떤 패턴을 따르는 경우에만 키가 유효한 것으로 간주하는 데이터 구조가있을 수 있습니다. 수업 안팎에서 이것을 사용하고 싶을 수 있습니다. 그러나 아직 다른 전역 함수를 만들고 싶지 않습니다.

def foo_key_is_valid(key):
    # code for determining validity here
    return valid

이 코드를 연결된 클래스로 그룹화하는 것이 좋습니다.

class Foo(object):

    @classmethod
    def is_valid(cls, key):
        # code for determining validity here
        return valid

    def add_key(self, key, val):
        if not Foo.is_valid(key):
            raise ValueError()
        ..

# lets me reuse that method without an instance, and signals that
# the code is closely-associated with the Foo class
Foo.is_valid('my key')

a를 사용하는 가장 큰 이유 @classmethod는 상속 될 대체 생성자에 있습니다. 이것은 다형성에서 매우 유용 할 수 있습니다. 예 :

class Shape(object):
    # this is an abstract class that is primarily used for inheritance defaults
    # here is where you would define classmethods that can be overridden by inherited classes
    @classmethod
    def from_square(cls, square):
        # return a default instance of cls
        return cls()

공지 사항 Shapeclassmethod를 정의하는 추상 클래스입니다 from_square때문에, Shape정말 정의되지 않은, 그것은 정말에서 자신을 도출하는 방법을 알고하지 않습니다 Square단순히 클래스의 기본 인스턴스를 반환 있도록.

상속 된 클래스는이 메서드의 자체 버전을 정의 할 수 있습니다.

class Square(Shape):
    def __init__(self, side=10):
        self.side = side

    @classmethod
    def from_square(cls, square):
        return cls(side=square.side)


class Rectangle(Shape):
    def __init__(self, length=10, width=10):
        self.length = length
        self.width = width

    @classmethod
    def from_square(cls, square):
        return cls(length=square.side, width=square.side)


class RightTriangle(Shape):
    def __init(self, a=10, b=10):
        self.a = a
        self.b = b
        self.c = ((a*a) + (b*b))**(.5)

    @classmethod
    def from_square(cls, square):
        return cls(a=square.length, b=square.width)


class Circle(Shape):
    def __init__(self, radius=10):
        self.radius = radius

    @classmethod
    def from_square(cls, square):
        return cls(radius=square.length/2)

사용법을 통해 인스턴스화되지 않은 모든 클래스를 다형 적으로 처리 할 수 ​​있습니다.

square = Square(3)
for polymorphic_class in (Square, Rectangle, RightTriangle, Circle):
    this_shape = polymorphic_class.from_square(square)

이것은 모두 훌륭하고 멋지다고 말할 수 있지만 @staticmethod동일한 다형성 동작을 수행 하는 데 사용할 수없는 이유는 무엇입니까?

class Circle(Shape):
    def __init__(self, radius=10):
        self.radius = radius

    @staticmethod
    def from_square(square):
        return Circle(radius=square.length/2)

대답은 할 수 있지만 Circle메서드에서 명시 적으로 호출해야 하므로 상속의 이점을 얻을 수 없다는 것입니다. 재정의하지 않고 상속 된 클래스에서 호출하면 Circle매번 얻을 수 있음을 의미 합니다.

Notice what is gained when I define another shape class that does not really have any custom from_square logic:

class Hexagon(Shape):
    def __init__(self, side=10):
        self.side = side

    # note the absence of classmethod here, this will use from_square it inherits from shape

Here you can leave the @classmethod undefined and it will use the logic from Shape.from_square while retaining who cls is and return the appropriate shape.

square = Square(3)
for polymorphic_class in (Square, Rectangle, RightTriangle, Circle, Hexagon):
    this_shape = polymorphic_class.from_square(square)

in class MyClass(object):
    '''
    classdocs
    '''
    obj=0
    x=classmethod
    def __init__(self):
        '''
        Constructor
        '''
        self.nom='lamaizi'
        self.prenom='anas'
        self.age=21
        self.ville='Casablanca'
if __name__:
    ob=MyClass()
    print(ob.nom)
    print(ob.prenom)
    print(ob.age)
    print(ob.ville)

참고URL : https://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod

반응형