如何获取实例引用的自己的名称?

How to get the own name of an instance reference?

是否可以在函数中获取调用函数的实例的引用名称? 在实例的引用调用的函数中,应该识别调用该函数的引用的名称。这可能吗?谢谢。

redCar = Car()
blackCar = Car()

redCar.carControl()
blackCar.carControl()


def carControl():

    if trafficJam == True:
        redCar.changeSpeed(500)
        redCar.warningLights(On)

        #is something like the following possible?
        "GetNameOfReferenceWhichCalledTheFunction".changeSpeed(500)
        "GetNameOfReferenceWhichCalledTheFunction".warningLight(On)
class Car:
    def __init__(self, name):
        self.name = name

    def change_speed(self, speed):
        print(self.name, ": speed =", speed)

    def car_control(self, traffic_jam):
        if traffic_jam:
            self.change_speed(0)
        else:
            self.change_speed(50)


red_car = Car("red")
black_car = Car("black")

red_car.car_control(True)
black_car.car_control(False)

输出:

red : speed = 0
black : speed = 50

实例不调用函数。您可以将 的 方法称为一个实例,这就是您对例如redCar.carControl()。因为carControl是方法,所以需要定义在class.

里面

但是是的,在该方法中,您可以访问 redCar - 因为它 作为参数传递 而您 需要 一个参数来接收它。按照惯例,我们使用名称 self 作为此参数。

请仔细研究示例:

traffic_jam = True

class Car:
    def control(self):
        if traffic_jam:
            # The display message will show some debug information that
            # identifies the object. It doesn't have the name `red_car`
            # built into it - it cannot, because you can use multiple names
            # for the same thing - but it is identified uniquely.
            print(self, "slowing down and putting on warning lights")

red_car = Car()
# When this call is made, the `red_car` will be passed to the method,
# which knows it as `self`.
red_car.control()

当使用class时,调用该方法的实例可以使用第一个参数访问,自动填充,一般称为self

class Car:
    def carControl(self):
        if trafficJam == True:
            self.changeSpeed(500)
            self.warningLights(On)

    def changeSpeed(self, value):
        self.speed = value


redCar = Car()
redCar.carControl()
redCar.changeSpeed(250)