python-behind class of property

method one:

  Effect Figure 1:

  Code One:

# Define a rectangle class 
class the Rectangle:
     # define initialization method 
    DEF  the __init__ (Self, width, height): 
        self.hidden_width = width 
        self.hidden_height = height 

    # define acquisition width, height of the method 
    DEF get_width (Self):
         return Self. hidden_width 

    DEF get_height (Self):
         return self.hidden_height 

    # custom modifications width, height method 
    DEF set_width (Self, width): 
        self.hidden_width = width 

    DEF set_height (Self, height):
        self.hidden_height = height 

    # define a rectangular area acquired method 
    DEF get_area (Self):
         return self.hidden_width * self.hidden_height 

# Create instance Rectangle 
r_one = Rectangle (3,4- )
 # outputs the print r_one of widh 
Print (r_one. get_width ())    # output 3 
# output of print r_one Area 
Print (r_one.get_area ())     # output 12 

# change width 
r_one.set_width (. 5 )
 Print (r_one.get_area ())      # output 20

Method Two:

  Effect Figure 2:

  Code II:

# 可以为对象的属性使用双下划线开头,__xxx
# 双下划线开头的属性,是对象的隐藏属性,隐藏属性只能在类的内部访问,无法通过对象访问
# 其实隐藏属性只不过是Python自动为属性改了一个名字
#   实际上是将名字修改为了,_类名__属性名 比如 __name -> _Person__name
class Person:
    def __init__(self,name):
        self.__name = name

    def get_name(self):
        return self.__name

    def set_name(self , name):
        self.__name = name        

p = Person('孙悟空')

# print(p.__name) # 报错:AttributeError: 'Person' object has no attribute '__name'
                  #__开头的属性是隐藏属性,无法通过对象访问
p.__name = '猪八戒' # 这个设置无效,不会报错
print(p._Person__name)
p._Person__name = '沙和尚'

print(p.get_name())

方法三: 常用的

  效果图三:

 

  代码三:

# 使用__开头的属性,实际上依然可以在外部访问,所以这种方式一般不用
#   一般会将一些私有属性(不希望被外部访问的属性)以_开头
#   一般情况下,使用_开头的属性都是私有属性,没有特殊需要不要修改私有属性
class Person:
    def __init__(self,name):
        self._name = name

    def get_name(self):
        return self._name

    def set_name(self,name):
        self._name = name

p = Person('牛一')

print(p._name)

 

Guess you like

Origin www.cnblogs.com/FlyingLiao/p/11332388.html