Python
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.
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 (eg, 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.
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).
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
345
print MyClass.i
123
链接地址: http://www.djcxy.com/p/54734.html
上一篇: 为什么使用RelayCommand或DelegateCommand而不是仅仅实现ICommand?
下一篇: 蟒蛇