python中封装_如何在Python中进行封装?

因此,Python 3提供了3个级别的数据访问:

1.public(public,没有特殊语法,publicVariable)

2.受保护(受保护,名称开头有一个下划线,即protectedVariable)

3.private(private,名称开头的两个下划线,privateVariable)。

最后一个是封装,这意味着限制对对象组件(变量,方法)的访问,你可以在类内定义方法,这样用户就可以看到变量,甚至可以更改它,如果他想给用户这样的特权,就依赖于程序员,所以简单地说,它实际上给了程序员调用什么是公共的什么是内部的

private和public是基本的和典型的用法,下面是一个例子

`class phone:

name="sony" #this variable is public

__number= 201090943929 #this is private one ,and also my actual number heheheheeh boii

def print_name(self): #this is public method

print ('my phone name is:', self.name)

def __print_number(self): #and private method

print (self.__number)

#actually we(the programmer not the user)-while writing the code- can give the user the user the authority to only

#see the value of the variable ,even to modify it by defining a metod inside the class

def print_private_number(self):

return self.__number

def modify_private_number(self,newNumber):

self.__number=newNumber

print(newNumber)

#now u can both prnt and modify the mumber with only the following methods

my_phone=phone()

my_phone.print_name() #now i called the public function , and cam simply print it as it's public (can be accessed)

print (my_phone.name) #same as here with variable

#Now if we tried to retrive private data ,or run private method

#its gonna end up with an error

#print (my_phone.__number)

#my_phone.__print_number()

print (my_phone.print_private_number())

my_phone.modify_private_number(5)

#so what if the programmer didnt allow us to see the number

#is that the end of the road ? nah ,we still can crack the system and both read and modify the private variables n functions

#hmmm am not gonna call it crack coz the langauage itself provides the programmer with

#syntatic tool that circumvent encapsulation

print (my_phone._phone__number)

#my_phone._phone__print_name()

`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值