是否有必要在Python的类中每次都包含__init__作为第一个函数?

时间:2022-05-17 18:16:25

In Python, I want to know that whether it is necessary to include __init__ as the first method while creating a class, as in the example below:

在Python中,我想知道是否有必要在创建类时包含__init__作为第一种方法,如下例所示:

class ExampleClass: 

    def __init__(self, some_message): 
        self.message = some_message 
        print "New Class instance created, with message:" 
        print self.message 

Also, why do we use self to call methods? Can someone explain the use of "self" in detail?

另外,为什么我们使用self来调用方法?有人可以详细解释“自我”的使用吗?

Also, why do we use pass statement in Python?

另外,为什么我们在Python中使用pass语句?

5 个解决方案

#1


45  

No, it isn't necessary.

不,没有必要。

For example.

class A(object):
    def f():
        print 'foo'

And you can of course use it, in this manner:

你当然可以这样使用它:

a = A()
a.f()

In fact you can even define a class in this manner.

实际上,你甚至可以用这种方式定义一个类。

class A:
    pass

However, defining __init__ is a common practice because instances of a class usually store some sort of state informtion or data and the methods of the class offer a way to manipulate or do something with that state information or data. __init__ allows us to initialize this state information or data while creating an instance of the class.

但是,定义__init__是一种常见做法,因为类的实例通常存储某种状态信息或数据,而类的方法提供了一种操作或对该状态信息或数据执行某些操作的方法。 __init__允许我们在创建类的实例时初始化此状态信息或数据。

Here is a complete example.

这是一个完整的例子。

class BankAccount(object):
    def __init__(self, deposit):
        self.amount = deposit

    def withdraw(self, amount):
        self.amount -= amount

    def deposit(self, amount):
        self.amount += amount

    def balance(self):
        return self.amount

# Let me create an instance of 'BankAccount' class with the initial
# balance as $2000.
myAccount = BankAccount(2000)

# Let me check if the balance is right.
print myAccount.balance()

# Let me deposit my salary
myAccount.deposit(10000)

# Let me withdraw some money to buy dinner.
myAccount.withdraw(15)

# What's the balance left?
print myAccount.balance()

An instance of the class is always passed as the first argument to a method of the class. For example if there is class A and you have an instance a = A(), whenever you call a.foo(x, y), Python calls foo(a, x, y) of class A automatically. (Note the first argument.) By convention, we name this first argument as self.

类的实例始终作为类的方法的第一个参数传递。例如,如果有A类并且你有一个实例a = A(),那么无论何时调用a.foo(x,y),Python都会自动调用A类的foo(a,x,y)。 (注意第一个参数。)按照惯例,我们将第一个参数命名为self。

#2


7  

In addition to other answers, one point in your question that has not been addressed :

除了其他答案之外,您问题中的一点尚未解决:

Is it necessary to include __init__ as the first function everytime in a class in Python?

是否有必要在Python的每个类中包含__init__作为第一个函数?

The answer is no. In the case you need a constructor, it can be located at any position of your code, although the conventional and logical place is the beginning.

答案是不。在您需要构造函数的情况下,它可以位于代码的任何位置,尽管传统的逻辑位置是开头。

#3


5  

You don't need to put it in your Class, it is the object constructor.

你不需要把它放在你的Class中,它是对象的构造函数。

You will need it if you want things to happen automatically to your object when it is instanciated.

如果你希望事物在实例化时自动发生在你的对象上,你将需要它。

#4


1  

No, it is not necessary to use the init in a class. It's a object constructor that define default values upon calling the class.

不,没有必要在类中使用init。它是一个对象构造函数,在调用类时定义默认值。

If you're programming in OOP manner and ought to have a basic structure of your class. You often will need this.

如果你是以OOP方式编程,并且应该有你班级的基本结构。你经常需要这个。

I read your other sub-question regarding

我读了你的其他子问题

Can u explain about the use of "self"??? – harsh Jul 28 '11 at 5:13

你能解释一下“自我”的使用吗? - 严厉于2011年7月28日5:13

Please refer to this post in *. There's a lot of useful links to help you better understand python's init function.

请参阅*中的这篇文章。有很多有用的链接可以帮助您更好地理解python的init函数。

Python __init__ and self what do they do?

Python __init__和self他们做了什么?

#5


0  

Sure that this not required.

当然,这不是必需的。

Please read more about defining python classes here and here.

请阅读更多有关在此处和此处定义python类的信息。

Read more about __init__ you can here and Python __init__ and self what do they do?.

阅读更多关于__init__你可以在这里和Python __init__和他们自己做什么?

In general __init__ is a kind of constructor that is called automatically and allows you to perform any additional actions(adding variables, calling any methods and so on - the idea is to have the ability to initialize instance since it is already created and now you may need to do something with it before proceeding - for example remember creation time or serializing its initial state and so on) while creating object. So if you don't need to do some special preparation you may skip using it.

通常__init__是一种自动调用的构造函数,允许您执行任何其他操作(添加变量,调用任何方法等等) - 这个想法是能够初始化实例,因为它已经创建了,现在你可以在创建对象之前,需要在继续之前做一些事情 - 例如记住创建时间或序列化其初始状态等等。因此,如果您不需要做一些特殊准备,您可以跳过使用它。

#1


45  

No, it isn't necessary.

不,没有必要。

For example.

class A(object):
    def f():
        print 'foo'

And you can of course use it, in this manner:

你当然可以这样使用它:

a = A()
a.f()

In fact you can even define a class in this manner.

实际上,你甚至可以用这种方式定义一个类。

class A:
    pass

However, defining __init__ is a common practice because instances of a class usually store some sort of state informtion or data and the methods of the class offer a way to manipulate or do something with that state information or data. __init__ allows us to initialize this state information or data while creating an instance of the class.

但是,定义__init__是一种常见做法,因为类的实例通常存储某种状态信息或数据,而类的方法提供了一种操作或对该状态信息或数据执行某些操作的方法。 __init__允许我们在创建类的实例时初始化此状态信息或数据。

Here is a complete example.

这是一个完整的例子。

class BankAccount(object):
    def __init__(self, deposit):
        self.amount = deposit

    def withdraw(self, amount):
        self.amount -= amount

    def deposit(self, amount):
        self.amount += amount

    def balance(self):
        return self.amount

# Let me create an instance of 'BankAccount' class with the initial
# balance as $2000.
myAccount = BankAccount(2000)

# Let me check if the balance is right.
print myAccount.balance()

# Let me deposit my salary
myAccount.deposit(10000)

# Let me withdraw some money to buy dinner.
myAccount.withdraw(15)

# What's the balance left?
print myAccount.balance()

An instance of the class is always passed as the first argument to a method of the class. For example if there is class A and you have an instance a = A(), whenever you call a.foo(x, y), Python calls foo(a, x, y) of class A automatically. (Note the first argument.) By convention, we name this first argument as self.

类的实例始终作为类的方法的第一个参数传递。例如,如果有A类并且你有一个实例a = A(),那么无论何时调用a.foo(x,y),Python都会自动调用A类的foo(a,x,y)。 (注意第一个参数。)按照惯例,我们将第一个参数命名为self。

#2


7  

In addition to other answers, one point in your question that has not been addressed :

除了其他答案之外,您问题中的一点尚未解决:

Is it necessary to include __init__ as the first function everytime in a class in Python?

是否有必要在Python的每个类中包含__init__作为第一个函数?

The answer is no. In the case you need a constructor, it can be located at any position of your code, although the conventional and logical place is the beginning.

答案是不。在您需要构造函数的情况下,它可以位于代码的任何位置,尽管传统的逻辑位置是开头。

#3


5  

You don't need to put it in your Class, it is the object constructor.

你不需要把它放在你的Class中,它是对象的构造函数。

You will need it if you want things to happen automatically to your object when it is instanciated.

如果你希望事物在实例化时自动发生在你的对象上,你将需要它。

#4


1  

No, it is not necessary to use the init in a class. It's a object constructor that define default values upon calling the class.

不,没有必要在类中使用init。它是一个对象构造函数,在调用类时定义默认值。

If you're programming in OOP manner and ought to have a basic structure of your class. You often will need this.

如果你是以OOP方式编程,并且应该有你班级的基本结构。你经常需要这个。

I read your other sub-question regarding

我读了你的其他子问题

Can u explain about the use of "self"??? – harsh Jul 28 '11 at 5:13

你能解释一下“自我”的使用吗? - 严厉于2011年7月28日5:13

Please refer to this post in *. There's a lot of useful links to help you better understand python's init function.

请参阅*中的这篇文章。有很多有用的链接可以帮助您更好地理解python的init函数。

Python __init__ and self what do they do?

Python __init__和self他们做了什么?

#5


0  

Sure that this not required.

当然,这不是必需的。

Please read more about defining python classes here and here.

请阅读更多有关在此处和此处定义python类的信息。

Read more about __init__ you can here and Python __init__ and self what do they do?.

阅读更多关于__init__你可以在这里和Python __init__和他们自己做什么?

In general __init__ is a kind of constructor that is called automatically and allows you to perform any additional actions(adding variables, calling any methods and so on - the idea is to have the ability to initialize instance since it is already created and now you may need to do something with it before proceeding - for example remember creation time or serializing its initial state and so on) while creating object. So if you don't need to do some special preparation you may skip using it.

通常__init__是一种自动调用的构造函数,允许您执行任何其他操作(添加变量,调用任何方法等等) - 这个想法是能够初始化实例,因为它已经创建了,现在你可以在创建对象之前,需要在继续之前做一些事情 - 例如记住创建时间或序列化其初始状态等等。因此,如果您不需要做一些特殊准备,您可以跳过使用它。