Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 即使没有',代码也可以工作;自我';方法中的属性_Python - Fatal编程技术网

Python 即使没有',代码也可以工作;自我';方法中的属性

Python 即使没有',代码也可以工作;自我';方法中的属性,python,Python,在下面的类中,类中的self参数methodcost被替换为另一个名称“insta”,但仍然有效。为什么? class car(): model='sedan' year=2016 price=775000 def cost(insta): print "Price of car is: ",insta.price c1=car() c1.model='SUV' c1.year=2017 c1.price=120000 c1.cost() c2=car(

在下面的类中,类中的self参数method
cost
被替换为另一个名称“insta”,但仍然有效。为什么?

class car():
   model='sedan'
   year=2016
   price=775000

   def cost(insta):
      print "Price of car is: ",insta.price

c1=car()
c1.model='SUV'
c1.year=2017
c1.price=120000
c1.cost()

c2=car()
c2.model='hatchback'
c2.year=2018
c2.price=600000
c2.cost()

命名
self
类方法的第一个参数只不过是一种约定。您的代码严格等同于:

def cost(self):
    print "Price of car is: ",self.price

然而,这种约定在任何地方都受到尊重,尽管我知道它只是一种约定,但我认为这是我第一次看到一个代码没有命名实例
self

命名
self
类方法的第一个参数只不过是一种约定。您的代码严格等同于:

def cost(self):
    print "Price of car is: ",self.price

然而,这个约定在任何地方都受到尊重,尽管我知道这只是一个约定,但我认为这是我第一次看到一个代码没有命名实例
self
当你将
c1
实例化为类
car
的对象时,
c1
得到这三个东西(属性)你给了它:一个
型号
,一个
年份
,一个
价格
。为了让
c1
知道您希望它的
cost()
方法访问它的
price
而不是
c2
的价格,例如,您(正确地)定义了
cost()
方法,将打印的
price
与调用
cost()
的对象的
price
相关联

self
这个词很常见,可能是因为给定了Python语法,当您在类对象上使用点表示法调用一个方法时(如
classObject.classMethod()
),您可能会比通常情况下更像是“在
classObject
上调用
classMethod()
”“将
someArgument
传递给
someFunction
”比方说,因为您没有将
classObject
放在
classMethod
的括号内,但关键是您在类定义中建立的关联(它将与“
self
”或“
insta
”或“
puppy
一起工作)“,只要你始终如一地使用所选的单词)。也许有一个有用的命名可以帮助说明在这个特定的上下文中发生了什么

def cost(myCar):
    print ("Price of car is: ", myCar.price)

因为您希望
myCar
cost
成为
myCar
price
。这就是
self
以一种更通用的方式(从而更易于阅读和维护)所做的。

当您将
c1
实例化为类对象
car
时,
c1
会得到您给它的三个属性:
模型
年份
价格
。为了让
c1
知道您希望它的
cost()
方法访问它的
price
而不是
c2
的价格,例如,您(正确地)定义了
cost()
方法,将打印的
price
与调用
cost()
的对象的
price
相关联

self
这个词很常见,可能是因为给定了Python语法,当您在类对象上使用点表示法调用一个方法时(如
classObject.classMethod()
),您可能会比通常情况下更像是“在
classObject
上调用
classMethod()
”“将
someArgument
传递给
someFunction
”比方说,因为您没有将
classObject
放在
classMethod
的括号内,但关键是您在类定义中建立的关联(它将与“
self
”或“
insta
”或“
puppy
一起工作)“,只要你始终如一地使用所选的单词)。也许有一个有用的命名可以帮助说明在这个特定的上下文中发生了什么

def cost(myCar):
    print ("Price of car is: ", myCar.price)

因为您希望
myCar
cost
成为
myCar
price
。这是self
以更一般的方式(因此更可读和可维护)所做的。

因为没有要求将该参数称为self
c1.cost()
只是
car.cost(c1)
的语法糖,所以
c1
只是一个参数,就像任何参数一样,可以调用任何东西。这个参数被称为
self
,这是惯例。因为没有要求这个参数被称为
self
c1.cost()
只是
car.cost(c1)
的语法糖,所以
c1
只是一个参数,就像任何参数一样,可以调用任何东西。按照惯例,这个参数称为
self