zoukankan      html  css  js  c++  java
  • 访问限制

    在class内部,可以有属性和方法,而外部代码可以通过直接调用实例方法来操作数据,
    
    这样,就隐藏了内部的复杂
    
    class Student(object):
    
        def __init__(self, name, score):
            self.name = name
            self.score = score
    
        def print_score(self):
            print '%s: %s' % (self.name, self.score)
    
    bart = Student('Bart Simpson', 98)
    print bart.name
    print bart.score
    bart.score = 59
    print bart.score
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
    Bart Simpson
    98
    59
    
    class Student(object):
    
        def __init__(self, name, score):
            self.name = name
            self.score = score
    
        def print_score(self):
            print '%s: %s' % (self.name, self.score)
    bart = Student('Bart Simpson', 98)
    print bart.name
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
    Bart Simpson
    
    class Student(object):
    
        def __init__(self, name, score):
            self.__name = name
            self.__score = score
    
        def print_score(self):
            print '%s: %s' % (self.__name, self.__score)
    bart = Student('Bart Simpson', 98)
    print bart.name
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
    Traceback (most recent call last):
      File "C:/Users/TLCB/PycharmProjects/untitled/a2.py", line 10, in <module>
        print bart.name
    AttributeError: 'Student' object has no attribute 'name'
    
    Process finished with exit code 1

  • 相关阅读:
    hdu 5726 GCD
    codeforces 982C Cut 'em all!
    codeforces 982B Bus of Characters
    codeforces 982A Row
    codeforces 983B XOR-pyramid
    codeforces 979D Kuro and GCD and XOR and SUM
    codeforces 983A Finite or not?
    codeforces 984B Minesweeper
    codeforces 979C Kuro and Walking Route
    codeforces 979B Treasure Hunt
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349605.html
Copyright © 2011-2022 走看看