python-Object-Oriented encapsulation 03

Source: Internet
Author: User

Then one of the above continues:

How to Hide

Hide a property (set to private) in Python, starting with a double underscore

class A:    __x = 1  # _A__x = 1    def __init__(self, name):        self.__name = name  # self._A__name = name    def __fun1(self):        print("run fun1.......")    def fun2(self):        self.__fun1()  # self._A__fun1()        print("run fun2.......")a = A("Astro")# print(a.x)  # 报错 无法访问到 x   AttributeError: 'A' object has no attribute 'x'print(A.__dict__)# {'__module__': '__main__', '_A__x': 1, ........}# _A__xprint(a._A__x)  # 1a.fun2()# run fun1.......# run fun2.......

?

Actually this is just a kind of morphing operation
Names that begin with all double underscores in a class, such as __x, are automatically formed: _ Class name __x form:
A._a__n is accessible, that is, this operation is not strictly restricting external access, just a syntactic distortion

Features of this variant:

    • Cannot be directly obj.__attrname outside the class
    • Can be used directly inside the class: Obj.__attrname
    • The __x defined in the subclass does not overwrite the __x defined by the parent class, because the subclass is formed: The subclass name is __x, and the parent class is formed: The parent class name __x, that is, when a property that begins with a double glide line is inherited to a subclass, the subclass cannot be overwritten.

The problems to be aware of in this deformation are:

1, this mechanism also does not really restrict us from the external direct access to properties, know the class name and property name can be spelled out name: _ Class Name __ property, and then you can access, such as A._a__n

2, the process of deformation occurs only once in the definition of the class, the assignment operation after the definition, does not deform

a.__g = "gd"print(a.__dict__)# {'_A__name': 'Astro', '__g': 'gd'}

3. In inheritance, the parent class can define a method as private if it does not want the subclass to overwrite its own method.

# 正常情况class A:    def foo(self):        print('A.foo')    def bar(self):        print('A.bar')        self.foo() #b.foo()class B(A):    def foo(self):        print('B.foo')b=B()b.bar()# A.bar# B.foo

?

?

# 私有化后class A:    def __foo(self): # #在定义时就变形为 _A__foo        print('A.foo')    def bar(self):        print('A.bar')        self.__foo() #self._A__foo()   只会与自己所在的类为准,即调用_A__faclass B(A):    def __foo(self): #_B__foo        print('B.foo')b=B()b.bar()# A.bar# A.foo

?

?

?

The meaning of encapsulation 1. Encapsulating data
# 封装数据属性:明确的区分内外class People:    def __init__(self, name, age):        self.__name = name        self.__age = age    def tell_info(self):        print("name:%s  age:%s" % (self.__name, self.__age))    # 我们可以根据根据需要对 传入的参数做限制    def set_info(self, name, age):        if not isinstance(name, str):  # 判断 传进来的 name 是不是 str 类型            print("name must be str type")            return        if not isinstance(age, int):            print("age must be int type")            return        self.__name = name        self.__age = agep = People("Astro", 15)p.tell_info()  # name:Astro  age:15# 通过调用 tell_info 这个接口,来间接访问 name 和 agep.set_info("茶水博士", 60)p.tell_info()  # name:茶水博士  age:60p.set_info(1111,222)  # name must be str type

?

?

2. Encapsulation method, Isolation complexity
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()# 插卡# 用户认证# 输入取款金额# 打印账单# 取款#----------------------------#取款是功能,而这个功能有很多功能组成:插卡、密码认证、输入金额、打印账单、取钱#对使用者来说,只需要知道取款这个功能即可,其余功能我们都可以隐藏起来,很明显这么做#隔离了复杂度,同时也提升了安全性
  • The TV itself is a black box, hiding all the details, but will certainly provide a bunch of buttons, these buttons are also the concept of the interface, so that the package is not pure meaning of the hidden!!!
  • The shutter is the method shoot camera provides for fools, which hides the complex photographic functions of the interior.

?

?

?

3. Characteristics (property)

What is attribute property

property is a special attribute that performs a function (function) and then returns a value when it is accessed

class People:    def __init__(self, name, weight, height):        self.name = name        self.weight = weight        self.height = height    @property    def bmi(self):        return self.weight / (self.height ** 2)p = People("astro", 55, 1.73)# print(p.bmi())  # 18.376825152861773# 我们想得到 bmi 这个值,需要调用 p.bmi() ,如果在 def bmi(self) 上面加 @property ,即可直接调用了print(p.bmi)  # 18.376825152861773p.height = 1.8print(p.bmi)  # 16.975308641975307p.bmi = 20  # 报错 AttributeError: can't set attribute

Why do you use property

After the function of a class is defined as an attribute, when the object is Obj.name, it is impossible to realize that its name is executed by a function and then computed, and that the use of this feature follows the principle of uniform access .

?

PS: Object-oriented encapsulation is available in three different ways:
"Public"
This is actually not encapsulated, is open to the outside
"Protected"
This encapsulation is not publicly available, but is publicly available to friends (friend) or subclass
"Private"
This package is not open to anyone.

?

Python does not have the syntax to build three of them into its own class mechanism, in C + + will generally be all the data is set to private, and then provide set and get method (interface) to setup and fetch, in Python through the property method can be implemented

class People:    def __init__(self, name):        self.__name = name    @property    def name(self):        return self.__name  # obj.name访问的是self.__NAME(这也是真实值的存放位置)    @name.setter    def name(self, val):        if not isinstance(val, str):  # 在设定值之前进行类型检查            print("姓名必须为字符串")            return        self.__name = val    @name.deleter    def name(self):        print("deleter....")        print("不允许删除....")p = People('astro')print(p.name)  # astro  此时可以直接访问 name 属性了p.name = 'Astro'print(p.name)  # Astro name 别改变了,执行了 @name.setter 下的方法p.name = 111  # 姓名必须为字符串del p.name  # deleter....   不允许删除....

python-Object-Oriented encapsulation 03

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.