Fay

封装

封装:目的对外提供接口,隐藏内部属性

1.数据属性: __x = 1 变形为: _A__x = 1

2.函数属性 def __foo(self):变形为: def _A__foo(self):

class A:

__x =10

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

def __foo(self): #函数属性 变形为def _A__foo(self):
print('run foo')

def bar(self):
self.__foo()

a = A('egon') #实例化一个对象
a._A__foo() #访问属性: 从实例化对象的角度访问类里面的方法即函数
print(a._A__x)
a.bar()

访问属性: 从类的的角度访问,方法同样

print(A._A__x) #从1
print(A._A__foo) #从<function A.__foo at 0x000000000217FAE8>

实例1:

class Teacher:

def init(self, name, age):
self.__name = name
self.__age = age
def tell_info(self):
print('姓名:%s,年龄:%s' % (self.__name, self.__age))
t = Teacher('egon', 18)

t.tell_info() #在外部访问内部的隐藏属性,就需要通过一个接口进行间接

实例2:

class ATM:
def __card(self):
print('插卡')

def __auth(self):
print('用户认证')

def __input(self):
print('输入取款金额')

def __print_bill(self):
print('打印账单')

def __take_money(self):
print('取款')

def withdraw(self):
self.__card()
self.__auth()
self.__input()
self.__print_bill()
self.__take_money()
a = ATM()
a.withdraw()

@property

是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值

property在类调用方法时,让感知不到是在调用方法

@property与封装(隐藏)的应用

class People:
def init(self,name): #定义属性 一步
self.__name=name
@property #使用者可以向访问数据属性一样直接访问,
def name(self):
return self.__name
p = People('egon')

print(p.name)
类定义为隐藏属性时,想要访问内部属性,只能开一个接口,定义一个方法进行访问来实现,但是从外部访问时是一个方法(函数)
此时加上@property之后,就可以直接在外部访问,而且不用加括号的形式访问

@property与类(非隐藏)的应用:

class Room:
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length
@property  ##使用者可以向访问数据属性一样直接访问,
def area(self):
    return self.width * self.length

r1=Room('alex',5,5)
print(r1.area,'====')
相当于@property是一种伪装使用者调用时,就相当于调他的方法,同时意味着方法必须有一个返回值

posted on 2018-09-27 20:42  sunny7  阅读(128)  评论(0)    收藏  举报

导航