我正在学习Python编程语言,我遇到了一些我不完全理解的东西。

在如下方法中:

def method(self, blah):
    def __init__(?):
        ....
    ....

self做什么?这意味着什么?这是强制性的吗?

__init__方法是做什么的?为什么有必要?(等)

我认为它们可能是面向对象结构,但我知道的不多。


当前回答

在这段代码中:

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

其他回答

__init__确实像一个构造函数。如果您希望任何类函数表现为非静态方法,则需要将“self”作为第一个参数传递给它们。self是类的实例变量。

我自己也很难理解。即使在看完答案之后。

要正确理解__init__方法,你需要理解self。

self参数

__init__方法接受的参数是:

def __init__(self, arg1, arg2):

但实际上我们只传递了两个参数:

instance = OurClass('arg1', 'arg2')

额外的论证从何而来?

当我们通过名称(或引用)访问对象的属性时。这里的instance是对新对象的引用。我们使用instance.printargs访问实例对象的printargs方法。

为了从__init__方法中访问对象属性,我们需要一个对象引用。

每当调用方法时,对主对象的引用将作为第一个参数传递。按照惯例,你总是调用方法self的第一个参数。

这意味着在__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 init方法

在这里,这个家伙写得很好,很简单:https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

阅读上面的链接作为参考:

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.

# 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()

试试这段代码。希望它能帮助很多像我一样的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 - __init__构造函数

医生-内情秀

析构函数删除对象- Jay