Day2 Advanced Object-Oriented

Access the visibility problem

In Python, access the properties and methods of only two, that is, public and private, if you want the property is private property in the name to be used as two underscores beginning, the following code can verify this.

# Private variable before the variable name with "__"
# If you have to use private variables, you can use dir (class ()) to view its real name.
# Private variables / functions can be called directly within the class.
# If you want to reflect a variable / function is particularly important that you can use "_"
class the Test:

        def __init__(self, foo):
              self.__foo = foo

        def __bar(self):
              print(self.__foo)
              print('__bar')


def main():
      test = Test('hello')
      # AttributeError: 'Test' object has no attribute '__bar'
      test.__bar()
      # AttributeError: 'Test' object has no attribute '__foo'
      print(test.__foo)


if __name__ == "__main__":
     main()

 

@property decorator

 Decorator when the need to pay attention to:

    1. decorator names, function names needs to be consistent.

    2. property need to declare, write setter, the order can not be reversed

    3. If you want just a little variable is accessed can not be modified, you can use accessor @property

    4. If you want to modify the accessor variables can build a modifier, or remove access control.

Class the Person (Object):

      def __init__(self, name, age):
            self._name = name
            self._age = age

      # Accessor - getter method for
     the @Property
      DEF name (Self):
           return self._name

     # Accessor - getter method for
    the @Property
    DEF Age (Self):
          return self._age

      # Modifier - setter Method
     @ age.setter
     DEF Age (Self, Age):
           self._age = Age

Play DEF (Self):
      IF self._age <= 16:
           Print ( '% S is playing chess flight.'% self._name)
      the else:
          Print ( '% S doudizhu being played.'% self._name)


def main():
      person = Person('王大锤', 12)
      person.play()
      person.age = 22
      person.play()
# person.name = '白元芳' # AttributeError: can't set attribute


if __name__ == '__main__':
     main()

 

"" "
In python class is dynamic.
" ","
Class the Num (Object):
       DEF the __init __ (Self):
           self.a = 1000

       DEF A (Self):
            Print (self.b,)


num = num ()
num.b = 1000000
# print (num.)
Print (num.b)
num. ()

Guess you like

Origin www.cnblogs.com/WANGRUNZE/p/11316510.html