Python类:在__init__()括号内明确编写属性的区别

huangapple go评论52阅读模式
英文:

Python Classes: Differences Between Explicitly Writing Attributes Inside __init__() Parentheses

问题

I am a Python beginner grinding through Python Crash Course by Eric Matthes. I am currently on chapter 9 Classes and Object Oriented Programming.

我是一个Python初学者,正在学习Eric Matthes的《Python Crash Course》第9章,关于类和面向对象编程。

I have the following code:

我有以下的代码:

class User: # Define the class
    """A simple attempt to model website users."""

    def __init__(self, first_name, last_name, age, username, city, country):
        self.first_name = first_name.title()
        self.last_name = last_name.title()
        self.age = age
        self.username = username
        self.city = city.title()
        self.country = country.title()
        self.login_attempts = 0

I understand that Python calls the __init__() method to create a new instance, stores the first_name, last_name, age, username, city, and country attributes. The author says that Python creates a new attribute called login_attempts.

我了解Python调用__init__()方法来创建一个新实例,存储first_namelast_nameageusernamecitycountry属性。作者说Python创建了一个名为login_attempts的新属性。

The author only shows this method, but I've seen some people online explicitly write the login_attempts attribute inside the __init__() method. Is there any difference between the two approaches? Is one of the approaches considered a "best practice?" I'd like to build good habits before I inconvenience people who use my code. Thank you!

作者只展示了这种方法,但我在网上看到一些人明确地在__init__()方法内部编写login_attempts属性。这两种方法之间有什么区别吗?有没有一种方法被认为是“最佳实践”?我想在给使用我的代码的人带来不便之前养成良好的习惯。谢谢!

英文:

I am a Python beginner grinding through Python Crash Course by Eric Matthes. I am currently on chapter 9 Classes and Object Oriented Programming.

I have the following code:

class User: # Define the class
"""A simple attempt to model website users."""

def __init__(self, first_name, last_name, age, username, city, country):
    self.first_name = first_name.title()
    self.last_name = last_name.title()
    self.age = age
    self.username = username
    self.city = city.title()
    self.country = country.title()
    self.login_attempts = 0

I understand that Python calls the __init__() method to create a new instance, stores the first_name, last_name, age, username, city, and country attributes. The author says that Python creates a new attribute called login_attempts.

The author only shows this method, but I've seen some people online explicitly write the login_attempts attribute inside the __init__() method. Is there any difference between the two approaches? Is one of the approaches considered a "best practice?" I'd like to build good habits before I inconvenience people who use my code. Thank you!

答案1

得分: 1

这取决于类别。如果在参数列表中添加login_attempts=0,那将允许调用者指定他们自己的值。但是,在__init__中定义的许多变量是供内部使用的,允许它们被覆盖是没有意义的。此外,请记住,如果只是添加login_attempts本身,那么调用者必须提供一个值。这就是为什么我添加了默认值(=0)的原因。

英文:

It depends on the class. If you add login_attempts=0 in the argument list, that would allow a caller to specify their own value. However, many variables defined in __init__ are for internal use, and there is no point in allowing them to be overridden. Also, remember that if you JUST add login_attempts by itself, then the caller MUST supply a value. That's why I added the default (=0).

答案2

得分: 1

如果它是一个参数,那么预期(实际上是必需的)调用者将数据作为参数传递。这就是函数参数的作用:它们指定函数需要执行其操作所需的数据。在初始化方法__init__的情况下,它指定了初始化正在创建的对象所需的数据。

然而,在这种情况下,login_attempts总是初始化为0,因为可以假定在用户尝试之前总是没有尝试。0似乎是一个很好的默认值,因为在开始计数之前总是计数为0;因此,是否有必要强制指定一个和值的起始值可能并不一定有用。

在某些情况下,将数据传递进来以便于测试可能是有意义的(例如,您可能希望测试当用户尝试登录两次后尝试第三次时会发生什么情况),但如果您还没有到需要担心测试便捷性的程度,是否需要允许调用者指定login_attempts的起始值呢?

英文:

If it's a parameter, then it's expected (actually, required) that the caller will pass in data as an argument. That's what the parameters of a function are for: they specify what data the function requires to do its action. In the case of the inializer method __init__, it specifies what data is required to initialize the object being created.

Here though, login_attempts is always initialized to 0, since, presumably, there are always 0 attempts until a user makes an attempt. 0 seems like a good default since a count is always 0 before you start counting; so it isn't necessarily useful to be forced to specify the starting value of a sum.

In some cases, it may make sense to pass the data in to ease testing (you may want to test what happens when a user with, say, two login attempts attempts a third), but if you aren't at the point where you're worried about ease of testing, do you need to allow the caller to specify what login_attempts should start as?

huangapple
  • 本文由 发表于 2023年6月13日 10:01:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定