python中的私有方法_Python中的私有方法

这里有很多很棒的东西,使用前导下划线进行模糊处理。就我个人而言,我从语言设计决策中受益匪浅,因为它减少了理解和使用新模块的时间。

但是,如果您决心实现私有属性/方法,并且您愿意不讲内容,那么您可以按照以下思路执行操作:from pprint import pprint

# CamelCase because it 'acts' like a class

def SneakyCounter():

class SneakyCounterInternal(object):

def __init__(self):

self.counter = 0

def add_two(self):

self.increment()

self.increment()

def increment(self):

self.counter += 1

def reset(self):

print 'count prior to reset: {}'.format(self.counter)

self.counter = 0

sneaky_counter = SneakyCounterInternal()

class SneakyCounterExternal(object):

def add_two(self):

sneaky_counter.add_two()

def reset(self):

sneaky_counter.reset()

return SneakyCounterExternal()

# counter attribute is not accessible from out here

sneaky_counter = SneakyCounter()

sneaky_counter.add_two()

sneaky_counter.add_two()

sneaky_counter.reset()

# `increment` and `counter` not exposed (AFAIK)

pprint(dir(sneaky_counter))

很难想象你会想这么做,但这是可能的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值