简体   繁体   English

调用方法的最佳方法-Python

[英]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? xymyclass()状态的一部分,还是它们在外部与类交互?

If x and y are not part of the state of the myclass() instance, they should not be stored in attributes. 如果xy不属于myclass()实例状态的一部分,则不应将它们存储在属性中。 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()方法并传入“其他”作为参数:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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