getter 和 setter 方法中的 python 变量名称如何与其构造函数中的名称不同? [英] How python variables name in getter and setter method are different to the name in its constructor?

查看:47
本文介绍了getter 和 setter 方法中的 python 变量名称如何与其构造函数中的名称不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 食谱中的一个属性示例感到困惑.

I am confused to a example of property from python cookbook.

class Person:
     def __init__(self, first_name):
          self.first_name = first_name
     @property
     def first_name(self): 
          return self._first_name
     @first_name.setter
     def first_name(self, value): 
          self._first_name = value
>>>people = Person('Tom')
>>>people.first_name
'Tom'
>>>people.first_name = 'Jack'
>>>people.first_name
'Jack'

当一个实例被创建时,一个参数分配给 self.first_name.但是,由于 self.first_name 与 self._first_name 不同,因此在调用 getter 属性时它将返回值 self._first_name.self.first_name 和 self._first_name 之间是什么关系?两个不同的变量如何相互关联?

When a instance is created, a argument assigns to self.first_name. However, it will return a value of self._first_name when getter property is called since self.first_name is distinguish to self._first_name. What is a relationship between self.first_name and self._first_name? How the two different variables related to each other?

推荐答案

self.first_name/people.first_name is the setter method-turned-property deffirst_name(self, value),而 self._first_name 是保存值的实际属性.构造函数使用 setter 来设置初始名称,它不直接分配给属性.

self.first_name/people.first_name is the setter method-turned-property def first_name(self, value), while self._first_name is the actual attribute holding the value. The constructor uses the setter to set the initial name, it doesn't directly assign to the property.

  1. 构造函数接收值作为函数参数
  2. 构造函数分配给属性 first_name 其中
  3. 调用setter def first_name
  4. 分配给属性 _first_name

请注意,构造函数中还有一个令人困惑的拼写错误,它应该是 self.first_name = first_name.

Note that there's another confusing typo in the constructor, it should be self.first_name = first_name.

这篇关于getter 和 setter 方法中的 python 变量名称如何与其构造函数中的名称不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆