类init和参数

时间:2014-08-26 13:09:58

标签: python init

我知道这是超级基本的Python内容,但这个概念并没有进入我的脑海。 我想念在__init__()

下即时创建对象的根本原因和结构

这是一个基本示例,我不明白放置self.tangerine="..."的原因以及为什么我添加self.order="order"一切正常,即使此参数未添加到__init__(self, order) < / p>

class MyStuff(object):

    def __init__(self):
        self.tangerine="And now a thousand years between"

    def apple(self):
        print "I AM CLASSY APPLE!" 

thing=MyStuff()
thing.apple()

print thing.tangerine

因此,为了深入研究这个简单的例子,我在init中添加了一个变量:

class MyStuff(object):

    def __init__(self, order):
        self.tangerine="And now a thousand years between"
        self.order="order"

    def apple(self):
        print "I AM CLASSY APPLE!" 

thing=MyStuff()
thing.apple()

print thing.tangerine

现在我收到一个错误:

Traceback (most recent call last):
  File "ex40_a.py", line 11, in <module>
    thing=MyStuff()
TypeError: __init__() takes exactly 2 arguments (1 given)

在我看来,那里有2个参数(橘子(自我)和秩序)。 有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

看起来不错,但我认为您希望将订单值输入您的对象。 此外,通常你不想在你的类上使用print语句,而是返回它们,然后将它们打印在你的代码中的其他地方(如果你需要)

class MyStuff(object):

def __init__(self, order):
    self.tangerine = "And now a thousand years between"
    self.order = order

def apple(self):
    return "I AM CLASSY APPLE!" 



thing = MyStuff("I like strings and integer values")

print thing.order
print thing.tangerine
print thing.apple()

输出:

  • 我喜欢字符串和整数值
  • 现在已经有一千年了
  • 我是CLASSY APPLE!

您可以使用以下命令指定要调用类的参数:

def __init__(self, order):
    self.order = order

如果您不想用任何东西调用您的类,只需使用字符串值,请执行以下操作:

def __init__(self):
    self.order = "order" 

答案 1 :(得分:1)

解剖您的第二个代码段:

# Define class named MyStuff which inherits from object
class MyStuff(object):

    # Define initializer method for class MyStuff
    # This method accepts 2 arguments: self and order
    # self will hold newly created instance of MyStuff
    def __init__(self, order):
        # Assign a string value to field tangerine of current instance
        self.tangerine="And now a thousand years between"
        # Assign a string value to field order of current instance
        self.order="order"
        # Note that second argument (order) was not used

    # Define apple method for class MyStuff
    # This method accepts 1 argument: self
    # self will hold the instance of MyStuff
    def apple(self):
        # Print a string to standard output
        print "I AM CLASSY APPLE!" 

# Create instance of MyStuff
# Initializer is called implicitly and self is set to new instance
# Second argument (order) is missing, so you get exception
thing=MyStuff()
# Correct invocation would be
thing = MyStuff("some string value")
# Call method apple of MyStuff instance - statement correct but won't be reached
# due to former exception
thing.apple()

# Print value of field tangerine of MyStuff instance to standard output - again
# statement correct but won't be reached due to former exception
print thing.tangerine

要阅读的内容:
- 实际和正式的功能/方法参数
- 字符串文字
- 当然还有Python classes