首页 > 解决方案 > 有什么区别?

问题描述

写这样的方法有什么区别:

class Battery():
    """A simple attempt to model a battery for an electric car."""

    def __init__(self, battery_size=60):
        """Initialize the batteery's attributes."""
        self.battery_size = battery_size

和这个:

class Battery():
    """A simple attempt to model a battery for an electric car."""

    def __init__(self):
        """Initialize the batteery's attributes."""
        self.battery_size = 60

在这两种情况下,如果我们不指定 battery_size 的值,Python 将使用默认值,即 60。两者都正常工作,但我只想知道区别只是为了清除我的概念。

标签: python

解决方案


和...之间的不同

def __init__(self, battery_size=60):
        """Initialize the batteery's attributes."""
        self.battery_size = battery_size

def __init__(self):
        """Initialize the batteery's attributes."""
        self.battery_size = 60

在第一个中,def __init__(self, battery_size=60):,battery_size是一个参数。=60显示默认值为battery_size60。

因此,如果您实例化该类:

x=Battery()

即使有参数也不会引发错误。这是因为您已经告诉 python 在battery_size提供值时将值设为 60 。但是如果你这样调用函数:

x=Battery(75)

的值battery_size现在是 75。这被分配给self.battery_size


在第二个例子中:

self.battery_size=60

在这里,它已经定义好了。所以无论你做什么,self.battery_size除非你做一些事情,比如加、减等,否则将永远保持 60。


推荐阅读