问题:Python的__init__和self是做什么的?
我正在学习Python编程语言,遇到了一些我不太了解的东西。
用类似的方法:
def method(self, blah):
def __init__(?):
....
....
怎么self
办?这是什么意思?它是强制性的吗?
该__init__
方法做什么?为什么有必要?(等等。)
我认为它们可能是OOP构造,但我不太了解。
I’m learning the Python programming language and I’ve came across something I don’t fully understand.
In a method like:
def method(self, blah):
def __init__(?):
....
....
What does self
do? What is it meant to be? Is it mandatory?
What does the __init__
method do? Why is it necessary? (etc.)
I think they might be OOP constructs, but I don’t know very much.
回答 0
在此代码中:
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
… self
变量表示对象本身的实例。大多数面向对象的语言将此作为隐藏参数传递给在对象上定义的方法。Python没有。您必须明确声明它。创建A
类的实例并调用其方法时,它将自动传递,如…
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
该__init__
方法大致代表了Python中的构造函数。调用时,A()
Python为您创建一个对象,并将其作为第一个参数传递给__init__
方法。任何其他参数(例如A(24, 'Hello')
)也将作为参数传递-在这种情况下,会引发异常,因为构造函数不期望它们。
In this code:
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
… the self
variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A
class and call its methods, it will be passed automatically, as in …
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
The __init__
method is roughly what represents a constructor in Python. When you call A()
Python creates an object for you, and passes it as the first parameter to the __init__
method. Any additional parameters (e.g., A(24, 'Hello')
) will also get passed as arguments–in this case causing an exception to be raised, since the constructor isn’t expecting them.
回答 1
是的,您是对的,这些是oop结构。
__init__
是一个类的构造函数。该self
参数是指对象的实例(如this
在C ++中)。
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
__init__
分配对象的内存时将调用该方法:
x = Point(1,2)
self
如果要将值与对象保持在一起,则在对象的方法内使用参数很重要。例如,如果您实现如下__init__
方法:
class Point:
def __init__(self, x, y):
_x = x
_y = y
您的x
和y
参数将存储在堆栈中的变量中,并且当init方法超出范围时将被丢弃。将这些变量设置为self._x
并将self._y
这些变量设置为Point
对象的成员(在对象的生存期内可访问)。
Yep, you are right, these are oop constructs.
__init__
is the constructor for a class. The self
parameter refers to the instance of the object (like this
in C++).
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
The __init__
method gets called when memory for the object is allocated:
x = Point(1,2)
It is important to use the self
parameter inside an object’s method if you want to persist the value with the object. If, for instance, you implement the __init__
method like this:
class Point:
def __init__(self, x, y):
_x = x
_y = y
Your x
and y
parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x
and self._y
sets those variables as members of the Point
object (accessible for the lifetime of the object).
回答 2
简短的说明性示例
希望对您有所帮助,这是我用来理解在类内部声明的变量与在__init__
函数内部声明的变量之间的区别的一个简单示例:
class MyClass(object):
i = 123
def __init__(self):
self.i = 345
a = MyClass()
print(a.i)
print(MyClass.i)
输出:
345
123
A brief illustrative example
In the hope it might help a little, here’s a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an __init__
function:
class MyClass(object):
i = 123
def __init__(self):
self.i = 345
a = MyClass()
print(a.i)
print(MyClass.i)
Output:
345
123
回答 3
简而言之:
self
正如它暗示的那样,它指向自身 -调用该方法的对象。也就是说,如果您有N个对象调用该方法,则将self.a
为N个对象中的每一个引用变量的单独实例。想象a
每个对象的N个变量副本 __init__
在其他OOP语言(例如C ++ / Java)中称为构造函数。基本思想是它是一种特殊的方法,当创建该Class的对象时会自动调用该方法
In short:
self
as it suggests, refers to itself– the object which has called the method. That is, if you have N objects calling the method, then self.a
will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable a
for each object __init__
is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a special method which is automatically called when an object of that Class is created
回答 4
__init__
确实像构造函数。如果希望它们充当非静态方法,则需要将“ self”作为第一个参数传递给任何类函数。“ self”是您的类的实例变量。
__init__
does act like a constructor. You’ll need to pass “self” to any class functions as the first argument if you want them to behave as non-static methods. “self” are instance variables for your class.
回答 5
试用此代码。希望它能帮助像我这样的许多C程序员学习Py。
#! /usr/bin/python2
class Person:
'''Doc - Inside Class '''
def __init__(self, name):
'''Doc - __init__ Constructor'''
self.n_name = name
def show(self, n1, n2):
'''Doc - Inside Show'''
print self.n_name
print 'Sum = ', (n1 + n2)
def __del__(self):
print 'Destructor Deleting object - ', self.n_name
p=Person('Jay')
p.show(2, 3)
print p.__doc__
print p.__init__.__doc__
print p.show.__doc__
输出:
Jay
Sum = 5
Doc - Inside Class
Doc - __init__ Constructor
Doc - Inside Show
Destructor Deleting object - Jay
Try out this code. Hope it helps many C programmers like me to Learn Py.
#! /usr/bin/python2
class Person:
'''Doc - Inside Class '''
def __init__(self, name):
'''Doc - __init__ Constructor'''
self.n_name = name
def show(self, n1, n2):
'''Doc - Inside Show'''
print self.n_name
print 'Sum = ', (n1 + n2)
def __del__(self):
print 'Destructor Deleting object - ', self.n_name
p=Person('Jay')
p.show(2, 3)
print p.__doc__
print p.__init__.__doc__
print p.show.__doc__
Output:
Jay
Sum = 5
Doc - Inside Class
Doc - __init__ Constructor
Doc - Inside Show
Destructor Deleting object - Jay
回答 6
类对象支持两种操作:属性引用和实例化
属性引用使用Python中所有属性引用使用的标准语法:obj.name。有效属性名称是创建类对象时在类命名空间中的所有名称。因此,如果类定义如下所示:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
then MyClass.i
和MyClass.f
是有效的属性引用,分别返回整数和函数对象。类属性也可以分配给它,因此您可以MyClass.i
通过赋值来更改其值。__doc__
也是有效的属性,返回属于该类的文档字符串:“简单示例类”。
类实例化使用函数表示法。只是假装类对象是一个无参数函数,它将返回该类的新实例。例如:
x = MyClass()
所述实例化操作(“呼叫”一类对象)来创建一个空对象。许多类喜欢创建具有定制为特定初始状态的实例的对象。因此,一个类可以定义一个名为的特殊方法__init__()
,如下所示:
def __init__(self):
self.data = []
当类定义__init__()
方法时,类实例化将自动__init__()
为新创建的类实例调用。因此,在此示例中,可以通过以下方式获取新的初始化实例:
x = MyClass()
当然,该__init__()
方法可能具有更大的灵活性。在这种情况下,提供给类实例化运算符的参数将传递给__init__()
。例如,
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i
摘自最终对我最大的帮助的官方文档。
这是我的例子
class Bill():
def __init__(self,apples,figs,dates):
self.apples = apples
self.figs = figs
self.dates = dates
self.bill = apples + figs + dates
print ("Buy",self.apples,"apples", self.figs,"figs
and",self.dates,"dates.
Total fruitty bill is",self.bill," pieces of fruit :)")
创建Bill类的实例时:
purchase = Bill(5,6,7)
你得到:
> Buy 5 apples 6 figs and 7 dates. Total fruitty bill is 18 pieces of
> fruit :)
Class objects support two kinds of operations: attribute references and instantiation
Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
then MyClass.i
and MyClass.f
are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i
by assignment. __doc__
is also a valid attribute, returning the docstring belonging to the class: “A simple example class”.
Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example:
x = MyClass()
The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__()
, like this:
def __init__(self):
self.data = []
When a class defines an __init__()
method, class instantiation automatically invokes __init__()
for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:
x = MyClass()
Of course, the __init__()
method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__()
. For example,
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i
Taken from official documentation which helped me the most in the end.
Here is my example
class Bill():
def __init__(self,apples,figs,dates):
self.apples = apples
self.figs = figs
self.dates = dates
self.bill = apples + figs + dates
print ("Buy",self.apples,"apples", self.figs,"figs
and",self.dates,"dates.
Total fruitty bill is",self.bill," pieces of fruit :)")
When you create instance of class Bill:
purchase = Bill(5,6,7)
You get:
> Buy 5 apples 6 figs and 7 dates. Total fruitty bill is 18 pieces of
> fruit :)
回答 7
自己弄不清楚这个问题。即使在这里阅读答案。
要正确理解__init__
方法,您需要了解自己。
自我参数
该__init__
方法接受的参数为:
def __init__(self, arg1, arg2):
但是我们实际上只传递了两个参数:
instance = OurClass('arg1', 'arg2')
多余的参数从何而来?
当我们访问对象的属性时,我们按名称(或按引用)进行操作。这里的实例是对我们新对象的引用。我们使用instance.printargs访问实例对象的printargs方法。
为了从__init__
方法内部访问对象属性,我们需要对对象的引用。
每当调用方法时,对主对象的引用都会作为第一个参数传递。按照惯例,您总是将第一个参数称为方法自身。
这意味着__init__
我们可以执行以下方法:
self.arg1 = arg1
self.arg2 = arg2
在这里,我们在对象上设置属性。您可以通过执行以下操作来验证这一点:
instance = OurClass('arg1', 'arg2')
print instance.arg1
arg1
这样的值称为对象属性。在这里,该__init__
方法设置实例的arg1和arg2属性。
来源:http : //www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method
Had trouble undestanding this myself. Even after reading the answers here.
To properly understand the __init__
method you need to understand self.
The self Parameter
The arguments accepted by the __init__
method are :
def __init__(self, arg1, arg2):
But we only actually pass it two arguments :
instance = OurClass('arg1', 'arg2')
Where has the extra argument come from ?
When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs.
In order to access object attributes from within the __init__
method we need a reference to the object.
Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self.
This means in the __init__
method we can do :
self.arg1 = arg1
self.arg2 = arg2
Here we are setting attributes on the object. You can verify this by doing the following :
instance = OurClass('arg1', 'arg2')
print instance.arg1
arg1
values like this are known as object attributes. Here the __init__
method sets the arg1 and arg2 attributes of the instance.
source: http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method
回答 8
请注意,self
实际上它可以是任何有效的python标识符。例如,我们可以从Chris B的示例中轻松编写:
class A(object):
def __init__(foo):
foo.x = 'Hello'
def method_a(bar, foo):
print bar.x + ' ' + foo
它的工作原理完全一样。但是,建议使用self,因为其他pythoner会更容易识别它。
note that self
could actually be any valid python identifier. For example, we could just as easily write, from Chris B’s example:
class A(object):
def __init__(foo):
foo.x = 'Hello'
def method_a(bar, foo):
print bar.x + ' ' + foo
and it would work exactly the same. It is however recommended to use self because other pythoners will recognize it more easily.
回答 9
基本上,在同一类的多个函数中使用变量时,需要使用’self’关键字。至于init,它用于设置默认值,以防该类中没有其他函数被调用。
Basically, you need to use the ‘self’ keyword when using a variable in multiple functions within the same class. As for init, it’s used to setup default values incase no other functions from within that class are called.
回答 10
__init__
本质上是一个函数,一旦创建并与相应的类匹配,该函数将“初始化” / “激活”特定对象的类的属性。 self
表示将继承这些属性的对象。
__init__
is basically a function which will “initialize”/“activate” the properties of the class for a specific object, once created and matched to the corresponding class.. self
represents that object which will inherit those properties.
回答 11
“自我”是对类实例的引用
class foo:
def bar(self):
print "hi"
现在我们可以创建foo的实例并对其调用方法,在这种情况下,Python将添加self参数:
f = foo()
f.bar()
但是,如果方法调用不在类实例的上下文中,则也可以传递它,下面的代码执行相同的操作
f = foo()
foo.bar(f)
有趣的是,变量名“ self”只是一个约定。下面的定义将完全相同。.尽管说过,这是非常严格的约定,应该始终遵循,但是它确实说明了语言的灵活性。
class foo:
def bar(s):
print "hi"
The ‘self’ is a reference to the class instance
class foo:
def bar(self):
print "hi"
Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:
f = foo()
f.bar()
But it can be passed in as well if the method call isn’t in the context of an instance of the class, the code below does the same thing
f = foo()
foo.bar(f)
Interestingly the variable name ‘self’ is just a convention. The below definition will work exactly the same.. Having said that it is very strong convention which should be followed always, but it does say something about flexible nature of the language
class foo:
def bar(s):
print "hi"
回答 12
只是演示的问题。
class MyClass:
def __init__(self):
print('__init__ is the constructor for a class')
def __del__(self):
print('__del__ is the destructor for a class')
def __enter__(self):
print('__enter__ is for context manager')
return self
def __exit__(self, exc_type, exc_value, traceback):
print('__exit__ is for context manager')
def greeting(self):
print('hello python')
if __name__ == '__main__':
with MyClass() as mycls:
mycls.greeting()
$ python3 class.objects_instantiation.py
__init__ is the constructor for a class
__enter__ is for context manager
hello python
__exit__ is for context manager
__del__ is the destructor for a class
Just a demo for the question.
class MyClass:
def __init__(self):
print('__init__ is the constructor for a class')
def __del__(self):
print('__del__ is the destructor for a class')
def __enter__(self):
print('__enter__ is for context manager')
return self
def __exit__(self, exc_type, exc_value, traceback):
print('__exit__ is for context manager')
def greeting(self):
print('hello python')
if __name__ == '__main__':
with MyClass() as mycls:
mycls.greeting()
$ python3 class.objects_instantiation.py
__init__ is the constructor for a class
__enter__ is for context manager
hello python
__exit__ is for context manager
__del__ is the destructor for a class
回答 13
在此代码中:
class Cat:
def __init__(self, name):
self.name = name
def info(self):
print 'I am a cat and I am called', self.name
在此__init__
充当类的构造函数,并在实例化对象时调用此函数。self
表示实例化对象。
c = Cat('Kitty')
c.info()
以上语句的结果如下:
I am a cat and I am called Kitty
In this code:
class Cat:
def __init__(self, name):
self.name = name
def info(self):
print 'I am a cat and I am called', self.name
Here __init__
acts as a constructor for the class and when an object is instantiated, this function is called. self
represents the instantiating object.
c = Cat('Kitty')
c.info()
The result of the above statements will be as follows:
I am a cat and I am called Kitty
回答 14
什么是自我呢?这是什么意思?是强制性的吗?
每个类方法(包括init)的第一个参数始终是对该类当前实例的引用。按照惯例,该参数始终命名为self
。在init方法中,self
指的是新创建的对象;在其他类方法中,它引用其方法被调用的实例。
Python 不会强迫您使用 “ self ”。您可以为其指定任何名称。但是请记住,方法定义中的第一个参数是对对象的引用。Python self
为您将参数添加到列表中。调用方法时不需要包含它。如果您没有提供self in init方法,则会收到错误消息
TypeError: __init___() takes no arguments (1 given)
什么是初始化方法吗?为什么有必要?(等等。)
init
是初始化的缩写。它是一个构造函数,当您创建类的实例时会调用该构造函数,而不必这样做。但是通常我们的做法是编写用于设置对象默认状态的init方法。如果您最初不愿设置对象的任何状态,则无需编写此方法。
What does self do? What is it meant to be? Is it mandatory?
The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self
. In the init method, self
refers to the newly created object; in other class methods, it refers to the instance whose method was called.
Python doesn’t force you on using “self“. You can give it any name you want. But remember the first argument in a method definition is a reference to the object. Python adds the self
argument to the list for you; you do not need to include it when you call the methods.
if you didn’t provide self in init method then you will get an error
TypeError: __init___() takes no arguments (1 given)
What does the init method do? Why is it necessary? (etc.)
init
is short for initialization. It is a constructor which gets called when you make an instance of the class and it is not necessary. But usually it our practice to write init method for setting default state of the object. If you are not willing to set any state of the object initially then you don’t need to write this method.
回答 15
# Source: Class and Instance Variables
# https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables
class MyClass(object):
# class variable
my_CLS_var = 10
# sets "init'ial" state to objects/instances, use self argument
def __init__(self):
# self usage => instance variable (per object)
self.my_OBJ_var = 15
# also possible, class name is used => init class variable
MyClass.my_CLS_var = 20
def run_example_func():
# PRINTS 10 (class variable)
print MyClass.my_CLS_var
# executes __init__ for obj1 instance
# NOTE: __init__ changes class variable above
obj1 = MyClass()
# PRINTS 15 (instance variable)
print obj1.my_OBJ_var
# PRINTS 20 (class variable, changed value)
print MyClass.my_CLS_var
run_example_func()
# Source: Class and Instance Variables
# https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables
class MyClass(object):
# class variable
my_CLS_var = 10
# sets "init'ial" state to objects/instances, use self argument
def __init__(self):
# self usage => instance variable (per object)
self.my_OBJ_var = 15
# also possible, class name is used => init class variable
MyClass.my_CLS_var = 20
def run_example_func():
# PRINTS 10 (class variable)
print MyClass.my_CLS_var
# executes __init__ for obj1 instance
# NOTE: __init__ changes class variable above
obj1 = MyClass()
# PRINTS 15 (instance variable)
print obj1.my_OBJ_var
# PRINTS 20 (class variable, changed value)
print MyClass.my_CLS_var
run_example_func()
回答 16
Python __init__
及其作用self
是什么?
怎么self
办?这是什么意思?它是强制性的吗?
该__init__
方法做什么?为什么有必要?(等等。)
给出的示例不正确,因此让我基于它创建一个正确的示例:
class SomeObject(object):
def __init__(self, blah):
self.blah = blah
def method(self):
return self.blah
当我们创建对象的实例时,将__init__
在对象创建后调用,以自定义对象。也就是说,当我们SomeObject
用'blah'
下面的方法(可能是任何东西)进行调用时,它将__init__
作为参数传递给函数blah
:
an_object = SomeObject('blah')
该self
参数是实例SomeObject
,将被分配到an_object
。
稍后,我们可能要在此对象上调用方法:
an_object.method()
进行点分查找,即将an_object.method
实例绑定到该函数的实例,并且该方法(如上所述)现在是“绑定”方法-这意味着我们无需将实例显式传递给方法调用。
方法调用获取实例是因为它绑定在点分查找上,并在调用时执行其编程要执行的任何代码。
隐式传递的self
参数self
由约定调用。我们可以使用其他任何合法的Python名称,但是如果将其更改为其他名称,您可能会被其他Python程序员感到羞耻和ed愧。
__init__
是一种特殊的方法,在Python数据模型文档中进行了介绍。在创建实例后立即调用它(通常通过__new__
-,尽管__new__
不是必需的,除非您将不可变的数据类型作为子类)。
Python __init__
and self
what do they do?
What does self
do? What is it meant to be? Is it mandatory?
What does the __init__
method do? Why is it necessary? (etc.)
The example given is not correct, so let me create a correct example based on it:
class SomeObject(object):
def __init__(self, blah):
self.blah = blah
def method(self):
return self.blah
When we create an instance of the object, the __init__
is called to customize the object after it has been created. That is, when we call SomeObject
with 'blah'
below (which could be anything), it gets passed to the __init__
function as the argument, blah
:
an_object = SomeObject('blah')
The self
argument is the instance of SomeObject
that will be assigned to an_object
.
Later, we might want to call a method on this object:
an_object.method()
Doing the dotted lookup, that is, an_object.method
, binds the instance to an instance of the function, and the method (as called above) is now a “bound” method – which means we do not need to explicitly pass the instance to the method call.
The method call gets the instance because it was bound on the dotted lookup, and when called, then executes whatever code it was programmed to perform.
The implicitly passed self
argument is called self
by convention. We could use any other legal Python name, but you will likely get tarred and feathered by other Python programmers if you change it to something else.
__init__
is a special method, documented in the Python datamodel documentation. It is called immediately after the instance is created (usually via __new__
– although __new__
is not required unless you are subclassing an immutable datatype).
回答 17
在这里,这家伙写得非常好而且很简单:https : //www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/
阅读以上链接作为对此的参考:
self
?那么,所有客户方法的自我参数又如何呢?它是什么?当然,这就是实例!换句话说,诸如提款之类的方法定义了从某个抽象客户帐户中提款的指令。调用jeff.withdraw(100.0)会将这些指令用于jeff实例。
因此,当我们说def withdraw(self,amount):时,我们的意思是,“这是您如何从Customer对象(我们称为self)和一个美元图形(我们称为amount)提取钱的方法。是被调用提现的Customer的实例,也不是我做类比。jeff.withdraw(100.0)只是Customer.withdraw(jeff,100.0)的简写,这是完全有效的(如果不经常出现)码。
init自我可能对其他方法有意义,但是init呢?当我们调用init时,我们正在创建一个对象,那么如何已经存在一个self?Python允许我们将self模式扩展到构造对象的时间,即使它并不完全适合。试想一下jeff = Customer(’Jeff Knupp’,1000.0)与调用jeff = Customer(jeff,’Jeff Knupp’,1000.0)相同;传入的jeff也成为结果。
这就是为什么当我们调用init时,我们通过说出self.name = name之类的东西来初始化对象。请记住,由于self是实例,所以这等效于说jeff.name = name,与jeff.name =’Jeff Knupp相同。同样,self.balance = balance与jeff.balance = 1000.0相同。在这两行之后,我们认为“客户”对象已“初始化”并可以使用。
小心你 __init__
经过初始化完成后,主叫方可以正确地假定对象就可以使用了。也就是说,在jeff = Customer(’Jeff Knupp’,1000.0)之后,我们可以开始对jeff进行入金和出金;jeff是一个完全初始化的对象。
Here, the guy has written pretty well and simple: https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/
Read above link as a reference to this:
self
? So what’s with that self parameter to all of the Customer
methods? What is it? Why, it’s the instance, of course! Put another
way, a method like withdraw defines the instructions for withdrawing
money from some abstract customer’s account. Calling
jeff.withdraw(100.0) puts those instructions to use on the jeff
instance.
So when we say def withdraw(self, amount):, we’re saying, “here’s how you withdraw money from a Customer object (which we’ll call self) and a dollar figure (which we’ll call amount). self is the instance of the Customer that withdraw is being called on. That’s not me making analogies, either. jeff.withdraw(100.0) is just shorthand for Customer.withdraw(jeff, 100.0), which is perfectly valid (if not often seen) code.
init self may make sense for other methods, but what about init? When we call init, we’re in the process of creating an object, so how can there already be a self? Python allows us to extend the self pattern to when objects are constructed as well, even though it doesn’t exactly fit. Just imagine that jeff = Customer(‘Jeff Knupp’, 1000.0) is the same as calling jeff = Customer(jeff, ‘Jeff Knupp’, 1000.0); the jeff that’s passed in is also made the result.
This is why when we call init, we initialize objects by saying things like self.name = name. Remember, since self is the instance, this is equivalent to saying jeff.name = name, which is the same as jeff.name = ‘Jeff Knupp. Similarly, self.balance = balance is the same as jeff.balance = 1000.0. After these two lines, we consider the Customer object “initialized” and ready for use.
Be careful what you __init__
After init has finished, the caller can rightly assume that the object is ready to use. That is, after jeff = Customer(‘Jeff Knupp’, 1000.0), we can start making deposit and withdraw calls on jeff; jeff is a fully-initialized object.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。