简体   繁体   中英

Best way to call a method - Python

I have these two classes, but I want to know what is the best way to call a function inside a class.

I like to use this one with attributes:

class myclass():
    def myfunction(self):
        return self.x + self.y

z = myclass()
z.x = 4
z.y = 3
print z.myfunction()

But I don't know if it's correct. Or should I be using this instead the last one?

class myclass():
    def myfunction(self,x,y):
        return x + y

z = myclass()
print z.myfunction(4,3)

It depends. Are x and y part of the state of myclass() or are they something external interacting with the class?

If x and y are not part of the state of the myclass() instance, they should not be stored in attributes. They would be passed in as arguments instead.

Lets say you have a car object, and you need to know what would happen to the car if it collided with something else. That 'something else' isn't part of the car, so you'd call the car.collide() method and pass in the 'something else' in as an argument:

car.collide(something_else)

but the car speed at the time of collision, as well as things like the mass of the car, are part of the state of the car object, so they are attributes:

car.speed = 80
car.mass = 1200
car.collide(something_else)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM