How does polymorphism work in Python?

前端 未结 4 1403
慢半拍i
慢半拍i 2020-12-02 15:31

I\'m new to Python... and coming from a mostly Java background, if that accounts for anything.

I\'m trying to understand polymorphism in Python. Maybe the problem is

4条回答
  •  甜味超标
    2020-12-02 15:48

    just nice example how it is possible to use same field of 2 totally different classes. It is more close to template.

    class A:
        def __init__(self, arg = "3"):
            self.f = arg
    a = A()
    a.f # prints 3
    class B:
        def __init__(self, arg = "5"):
            self.f = arg
    b = B()
    b.f # prints 5
    
    
    def modify_if_different(s,t, field):
        if s.__dict__[field] != t.__dict__[field]:
            t.__dict__[field]  = s.__dict__[field]
        else:
            s.__dict__[field]  = None
    
    modify_if_different(a,b,"f")
    b.f # prints 3
    a.f # prints 3
    

提交回复
热议问题