亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【2023年】第48天 私有函數(變量)

標簽:
Python

一、私有函数(变量)

  • 无法被实例化后的对象调用的类中的函数与变量
  • 类内部可以调用私有函数与变量
  • 只希望类内部业务调用使用,不希望被使用者调用。
  • 在变量或函数前添加_(2个下横线),变量或者函数名后无需添加。
class Person(object):
	def __init__(self, name):
		self.name = name
		self.__age = 33
	def dump(self):
		print(self.name, self.__age)
	def __cry(self):
		return 'I want cry'
  • 上述代码中的age虽然是私有的,但是我们依然可以通过self调用。
# coding:utf-8

class Cat(object):
    __cat_type = 'cat'

    def __init__(self, name, sex):
        self.name = name
        self.__sex = sex

    def run(self):
        result = self.__run()
        print(result)

    def __run(self):
        return f'{self.__cat_type}, 小猫 {self.name} {self.__sex}开学的奔跑'

    def dump(self):
        result = self.__dump()
        print(result)

    def __dump(self):
        return f'{self.__cat_type} 小猫 {self.name} {self.__sex} 开学的跳着'

cat = Cat(name='小谬', sex='boy')
cat.run()
cat.dump()
print(dir(cat))
print(cat._Cat__dump())
print(cat._Cat__cat_type)
  • 涉及私有函数和私有属性的构造。

二、python中的封装

  • 将不对外的私有属性或方法通过可对外使用的函数而使用(类中定义私有的,只有类内部使用,外部无法访问)
  • 这样做的主要原因:保护隐私,明确区分内外。
# coding:utf-8

class Parent(object):

    def __hello(self, data):
        print('hello %s' % data)

    def helloworld(self):
        self.__hello('world')


if __name__ == '__main__':
    p = Parent()
    p.helloworld()
    
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消