Python: accessor and modifier

  Class property

  _ Attribute name is not recommended visit, suggesting that this property is a protected name

  Would like to visit may be operated by the corresponding property getters (accessors) and the setter (modifier) ​​Method

  Use @property wrapper to wrap getter and setter methods so that safe and convenient access to the property

  __ attribute name not visit

  property 英[ˈprɒpəti]

  United States [prɑːpərti]

  . N belongings; property; property; real property; real estate; houses and courtyards; manor;

  [例句]Richard could easily destroy her personal property to punish her for walking out on him

  Richard can easily destroy her personal property to punish her betrayal of him.

  [Other] complex: properties

  Access is not recommended to visit the property by decorators

  # @Property decorator

  class A:

  def __init__(self):

  self._x = 10

  self._y = 20

  @property

  def y(self):

  return self._y

  @property

  def x(self):

  return self._x

  a = A()

  print(a.x, a.y)

  setter is not recommended to modify the properties of visit

  class Person(object):

  def __init__(self, name, age):

  self._name = name

  self._age = age

  # Getter accessor method

  @property

  def name(self):

  return self._name

  # Getter accessor method

  @property Zhengzhou good gynecological hospital http://www.zzkedayy.com/

  def age(self):

  return self._age

  # Modifier setter method

  @age.setter

  def age(self, age):

  self._age = age

  def play(self):

  if self._age <= 16:

  print ( '% s being draw circles'% self._name)

  else:

  print('%' % self._name)

  def main():

  person = Person ( 'King sledgehammer', 12)

  person.play()

  # Modify the properties

  person.age = 22

  person.play()

  # If we change the name attribute

  person.name = 'she Broken Sword' # AttributeError: can not set attribute (non-modifiable)

  if __name__ == '__main__':

  main()


Guess you like

Origin blog.51cto.com/14503791/2466910