【问题标题】:How to get the own name of an instance reference?如何获取实例引用的自己的名称?
【发布时间】:2020-03-25 21:40:51
【问题描述】:

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

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)

【问题讨论】:

  • id Car 是如何定义的?因为如果它是一个类,那么你的 python 代码是无效的。而且是无效的,因为方法没有括号
  • 你不能只做self.changeSpeed(500)吗?
  • 看到您的编辑,我猜这是无效且未经测试和未经尝试的代码?而是一个愿望,因为Car 是未定义的
  • 是的,它未经测试,或多或少是一个愿望
  • 在这一点上,学习语言教程可能比询问这样的小事要好。

标签: python python-3.x reference instance


【解决方案1】:

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

但是是的,在该方法中,您可以访问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()

【讨论】:

  • 完美,我明白了。非常感谢。
【解决方案2】:

在使用类时,调用方法的实例可以使用第一个参数访问,自动填充,一般称为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)

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多