包含作为属性与方法

时间:2019-02-02 12:34:19

标签: python oop initialization

在上OOP许多初学者的Python教程,仅取决于{{} 1}经常包括的方法。

例如,a YouTube video包括以下示例:

self

什么因素会影响在方法中而不是属性中包含类似内容的决定?

例如:

class Employee:

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'

    def fullname(self):
        return '{} {}'.format(self.first, self.last)

2 个答案:

答案 0 :(得分:2)

想象一下:

class Employee:
    def __init__(self, first, last):
        self.first = first
        self.last = last
        self.fullname = f'{first} {last}'

结果是:

>>> e = Employee('John', 'Smith')
>>> e.fullname
'John Smith'
>>> e.first = 'Pete'
>>> e.fullname
'John Smith'

这意味着在更改名字或姓氏时不会更新全名。

如果我们改为使用属性:

class Employee:
    def __init__(self, first, last):
        self.first = first
        self.last = last

    @property
    def fullname(self):
        return f'{self.first} {self.last}'

我们得到:

>>> e = Employee('John', 'Smith')
>>> e.fullname
'John Smith'
>>> e.first = 'Pete'
>>> e.fullname
'Pete Smith'

如您所见,全名现在将在名字或姓氏更新时更新,并且不会同步。

答案 1 :(得分:0)

File.AppendAllText(@"G:\Sniffers\path.txt", destPath + " : Licence path\n"); 作为方法使fullname的“属性”具有动态性。如果您更改名字和/或姓氏并呼叫fullname,它将返回预期的全名。

在您发布的代码中,不清楚组成fullname的逻辑是什么。如果严格来说是“ first.last@company.com”,那么也有必要为其制定一种方法。但是从另一方面来说,电子邮件通常是用户提供的东西,更改名称并不一定意味着更改电子邮件。

现在,为什么我在上面的引号中加上“属性”:Python(和许多其他语言)的概念为properties。因此,全名实际上是从第一个到最后一个动态组成的属性。

相关问题