类初始化和参数

2024-06-02 09:56:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这是超级基本的Python东西,但是我没有想到这个概念。 我错过了在__init__()下实例化对象的基本原因和结构

这是一个基本的例子,我不明白为什么要把self.tangerine="..."放在那里,为什么我添加self.order="order"所有的东西都能正常工作,即使这个参数没有被添加到__init__(self, order)

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中添加了一个变量:

^{pr2}$

现在我得到一个错误:

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

在我看来有两个论点(橘子(自我)和秩序)。 有人能帮我吗?在


Tags: 对象实例self概念appleinitdeforder
2条回答

第二段代码的剖析:

# 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

看起来不错,但我想你想把订单值输入你的对象。 另外,一般情况下,您不希望在类上使用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()

输出:

  • 我喜欢字符串和整数值
  • 现在是一千年前
  • 我是一流的苹果!在

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

^{pr2}$

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

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

相关问题 更多 >