python - 有什么区别?
问题描述
写这样的方法有什么区别:
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。两者都正常工作,但我只想知道区别只是为了清除我的概念。
解决方案
和...之间的不同
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_size
60。
因此,如果您实例化该类:
x=Battery()
即使有参数也不会引发错误。这是因为您已经告诉 python 在未battery_size
提供值时将值设为 60 。但是如果你这样调用函数:
x=Battery(75)
的值battery_size
现在是 75。这被分配给self.battery_size
在第二个例子中:
self.battery_size=60
在这里,它已经定义好了。所以无论你做什么,self.battery_size
除非你做一些事情,比如加、减等,否则将永远保持 60。
推荐阅读
- android - 如何在 Android Studio 中同时水平滚动多个 TextView?
- android-webview - Appium Start Inspector Session webview 菜单栏区域无法点击选择元素
- flutter - setState() 会影响 Flutter 的性能吗?
- python - Dockerfile 中的 PYTHONUNBUFFERED 有什么作用?
- woocommerce - Woocommerce“wc-template-functions.php”文件中的致命错误
- java - 循环内发生数据库错误时如何回滚整个过程?
- android - 我在使用 firebase 时遇到问题,我正在尝试获取一个列表,但即使有值,该列表也不会显示在我的回收视图中
- sql-server - 如何使用 Nifi 将 Azure DataLakeStorage 中的 .parquet 数据转储到 Microsoft SQL Server 数据库?
- javascript - 是否应该在节点中收听 http.ClientReuqest 的“错误”事件?
- arrays - 将数据从 .csv 传输到结构数组,然后对其进行排序以将其保存在不同的文件中