Non-member vs member functions in Python

前端 未结 5 1799
清歌不尽
清歌不尽 2021-02-18 21:54

I\'m relatively new to Python and struggling to reconcile features of the language with habits I\'ve picked up from my background in C++ and Java.

The latest issue I\

5条回答
  •  无人共我
    2021-02-18 22:04

    As scale relies on member-wise multiplication of a vector, I would consider implementing multiplication as a method and defining scale to be more general:

    class Vector(object):
        def __init__(self, dX, dY):
            self._dX = dX
            self._dY = dY
    
        def __str__(self):
            return "->(" + str(self._dX) + ", " + str(self._dY) + ")"
    
        def __imul__(self, other):
            if other is Vector:
                self._dX *= other._dX
                self._dY *= other._dY
            else:
                self._dX *= other
                self._dY *= other
    
            return self
    
    def scale(vector, scalar):
        vector *= scalar
    

    Thus, the class interface is rich and streamlined while encapsulation is maintained.

提交回复
热议问题