Java教程

【2023年】第48天 私有函数(变量)

本文主要是介绍【2023年】第48天 私有函数(变量),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、私有函数(变量)

  • 无法被实例化后的对象调用的类中的函数与变量
  • 类内部可以调用私有函数与变量
  • 只希望类内部业务调用使用,不希望被使用者调用。
  • 在变量或函数前添加_(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()
    
这篇关于【2023年】第48天 私有函数(变量)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!