在类中编写代码和在Python中的def __init __(self)有什么区别? [英] What is the difference writing code in a class and in def __init__(self) in Python?

查看:151
本文介绍了在类中编写代码和在Python中的def __init __(self)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我理解当一个类被调用时,它将在任何事情之前运行 __ init __ 中的代码。我仍然没有看到它们之间的区别,并直接在类下面写代码。



例如:

  class main():
x = 1

def disp(self):
print self.x





  class main():
def __init __(self):
self.x = 1

def disp(self):
print self.x
pre>

对我来说,两者都有相同的功能。

解决方案

这里有一个是一个几个关键的区别,在 __ init __ 之间,写在类下面,以及你写的。



使用 x = 1



首先,你是对的 - 这两个代码有效(特别是因为我们在这里使用 int 对象,这对于可变对象是不同的):



请注意,他们不会实际上执行相同的操作 - 请参阅对此答案的评论以了解详情。

  class main(object):
x = 1


  class main(object):
def __init __(self):
self.x = 1

这就是为什么许多非标准Python库,例如 mongoengine django 模型,有一个标准,你在其中创建类,而不使用 __ init __ 语句,以便不覆盖内置的,但仍允许您创建类属性,例如, Django示例:

  class mymodel(models.model):
name = models。 CharField(max_length = 20)
url = models.UrlField()

其他海报指出,两者之间有一个区别,当 x = 1 __ init __ 函数之外,它是类本身的一部分,即使没有初始化 - 参见 Zagorulkin Dmitry 的更多细节的答案。



其他注意事项



更多用于 __ init __ ,而不仅仅是设置变量。最重要的一个是在初始化期间接受参数的能力。据我所知,没有一个方法,没有 __ init __ 函数。



让我们假设我们创建一个 Person 类,当我们创建一个 Person 时,我们提供他们的年龄,然后自动计算出生年份。

  import datetime 
class Person(object):
def __init __(self,age):
self .age = age
self.birth_year =(datetime.date.today() - datetime.timedelta(days = age * 365))。year

使用中:

 > ;> joe = Person(23)
>>> joe.age
23
>>> joe.birth_year
1990

这不可能没有 __ init __ ,因为我们' t否则传递初始化 age 参数。


Possible Duplicate:
Variables inside and outside of a class __init__() function

I understand that when a class is called it will run the code in __init__ before anything. I still don't see the difference between that, and writing the code directly under the class.

For example:

class main():
  x = 1

  def disp(self):
    print self.x

class main():
  def __init__(self):
    self.x = 1

  def disp(self):
    print self.x

To me, both have the same functionality. (Maybe I am missing out something.) I would like to know which is more (ahem) pythonic and why.

解决方案

There are a couple key differences here, both between __init__ and writing it just under the class, as well as what you wrote.

Working with x = 1

First, you are right--these two items of code do effectively the same thing for your purposes (specifically because we're working with int objects here, this would be different for mutable objects):

Note that they don't actually do the same thing--please see the comments on this answer for clarification.

class main(object):
    x = 1


class main(object):
    def __init__(self):
        self.x = 1

This is why many non-standard Python libraries, like mongoengine and django models, have a standard where you create classes without using an __init__ statement so as not to override the built-in one, but still allowing you to create class attributes, e.g., a Django example:

class mymodel(models.model):
    name = models.CharField(max_length=20)
    url = models.UrlField()

However, as the other poster points out, there is a difference between the two in that when x=1 is outside of the __init__ function, it is part of the class itself even when not intialized--see Zagorulkin Dmitry's answer for more detail on that. In most cases, though, that distinction won't be relevant for you.

Other considerations

There are more uses for __init__ beyond just setting variables. The most important one offhand is the ability to accept arguments during initialization. To my knowledge, there is not a way to do this without an __init__ function. I'll show you what I mean by this in this example.

Let's say we're creating a Person class, and when we create a Person, we supply their age, and then their birth year is automatically calculated from that for us.

import datetime
class Person(object):
    def __init__(self, age):
        self.age = age
        self.birth_year = (datetime.date.today() - datetime.timedelta(days=age*365)).year

In use:

>>>joe = Person(23)
>>>joe.age
23
>>>joe.birth_year
1990

This wouldn't be possible without __init__, since we couldn't pass the initialization the age argument otherwise.

这篇关于在类中编写代码和在Python中的def __init __(self)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆