当我们可以使用简单的方法时,为什么要使用 __init__ 和 self
Why use __init__ and self when we can use simple methods
当我们可以使用方法时,我对为什么在定义 class 时使用 init 和 self 感到困惑。下面的例子说明了我的困惑:
示例 1 利用 init 和 self:
class car:
def __init__(self,model,color):
self.model = model
self.color = color
def show(self):
print('model is', self.model)
print('color is', self.color)
audi = car('audi a4', 'blue')
ferrari = car('ferrari 488','green')
audi.show()
model is audi a4
color is blue
ferrari.show()
model is ferrari 488
color is green
示例2使用方法:
class car:
def audifeatures(car, model, color):
print ('car is', car, 'model is', model, 'color is', color)
def ferrarifeatures(car, model, color):
print ('car is', car, 'model is', model, 'color is', color)
car.audifeatures('audi','x8','black')
car is audi model is x8 color is black
car.ferrarifeatures('ferrari','f5','red')
car is ferrari model is f5 color is red
您的 print
语句生成的短语 "car is audi model is x8 color is black" 只是 个单词 ;您只是在形成一个使用 words "model" 和 "color" 的字符串(而 car
class 基本上是不相关的)。
init
和 self
是关于定义具有属性 的 对象,以便您可以进行 object-based 编程; car
class 生成一个 实例 实际上 有 模型和颜色。
这就像重复短语 "I am six feet tall" 的鹦鹉和实际 是 六英尺高的人之间的区别。
当我们可以使用方法时,我对为什么在定义 class 时使用 init 和 self 感到困惑。下面的例子说明了我的困惑:
示例 1 利用 init 和 self:
class car:
def __init__(self,model,color):
self.model = model
self.color = color
def show(self):
print('model is', self.model)
print('color is', self.color)
audi = car('audi a4', 'blue')
ferrari = car('ferrari 488','green')
audi.show()
model is audi a4
color is blue
ferrari.show()
model is ferrari 488
color is green
示例2使用方法:
class car:
def audifeatures(car, model, color):
print ('car is', car, 'model is', model, 'color is', color)
def ferrarifeatures(car, model, color):
print ('car is', car, 'model is', model, 'color is', color)
car.audifeatures('audi','x8','black')
car is audi model is x8 color is black
car.ferrarifeatures('ferrari','f5','red')
car is ferrari model is f5 color is red
您的 print
语句生成的短语 "car is audi model is x8 color is black" 只是 个单词 ;您只是在形成一个使用 words "model" 和 "color" 的字符串(而 car
class 基本上是不相关的)。
init
和 self
是关于定义具有属性 的 对象,以便您可以进行 object-based 编程; car
class 生成一个 实例 实际上 有 模型和颜色。
这就像重复短语 "I am six feet tall" 的鹦鹉和实际 是 六英尺高的人之间的区别。