是否可以在函数中获取正在调用函数的实例的引用名称?在由实例的引用调用的函数中,应识别调用该函数的引用的名称。这可能吗?谢谢。
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)
实例不调用函数。您可以调用method of实例,例如, 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()
使用类时,可以使用自动填充的第一个参数(通常称为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)
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)