Home > OS >  Python object. How to pass a value to one specific method
Python object. How to pass a value to one specific method

Time:10-17

I have a Python object that represents a camera dolly that moves along a track. The class can store and report its position along the track. I have three methods:

  1. MoveBy - which gets the distance from another object (Movie.yIncrement)
  2. MoveTo - which I want to pass a value between 0 and the length of the track
  3. Reset - which should return the dolly to the start of the track

I think I've misunderstood how to call the MoveTo method with a value?

class Dolly:
    name = "Dolly"
    DollyOrigin2CamCL = 30 #subject to actually constructing the dolly
    DollyLengthY = 130 #subject to actually constructing the dolly
    #constructor
    def __init__(self, pos):
        self.pos = pos 
        #reset() # <---can I do this here?
    #methods
    def moveBy(self):
        print("moving by "   Movie.yIncrement)
        #check pos   incrementY doesn't exceed Track.length - camera centreline to dolly end distance (need to set this up)
        #Dolly motor  control to move 'increment' distance away from origin
        #ensure that the code that calls this method updates Dolly.pos, by the incrementY
    def moveTo(self,goTo):
        print("moving directly to position "   self.goTo)
        #Make sure dolly doesn't run off the Track.startY or Track.endY (inclding the dolly size)
    def reset(self):
        print("returning to startY ("   Movie.startY   ")")
        #Make sure dolly doesn't run off the Track.startY - include dolly local 0 to camera centreline offset
        #After reset, assert pos is zero
    def stepRegime(self):
        #Take Movie.yIncrement and work out which type of motor control to use to traverse quickly and accurately
        print("resetting")

D1 = Dolly(20)
print(D1.pos)
print(D1.DollyOrigin2CamCL)
print(D1.DollyLengthY)
D1.moveBy
D1.moveTo(100)

CodePudding user response:

I think you may have forgot to update the attribute when calling the moveTo()method.

It should be something like:

    def moveTo(self,goTo):
        self.goTo = goTo
        print(f"moving directly to position {self.goTo} ")
        #Make sure dolly doesn't run off the Track.startY or Track.endY (inclding the dolly size)

Also, even if a method does not require extra parameters, you need to call them by using the parentheses, otherwise you're just accessing the function without executing it. So last part of your code should be:

D1.moveBy()
D1.moveTo(100)

Regarding instead the comment in your constructor. You can indeed call methods of the instance from the constructor. When calling a method of the instance inside a class you need to first access the instance, by using the self variable and then call the methods you wish to call


    #constructor
    def __init__(self, pos):
        self.pos = pos 
        self.reset() # <---now you can
  • Related