Package python 28

Object-oriented - A package

A: a package Introduction

Package three characteristics of object-oriented characteristics of the core of a
package <-> Integration

Second, the packaging operation attributes Hide

1, how to hide: in addition __ prefix before the attribute name, will achieve a hidden attribute of external effects
of the hidden problems that need attention:

I: In the property outside can not directly access the beginning of the decline in the double line, but you know the class and attribute names you can spell the name: class name _ __ property, then you can visit, such as Foo._A__N,
so that this There is no limit external access and operate on the ground in the strict sense, just a deformation of the grammatical meaning.


class Foo:
    __x = 1  # _Foo__x

    def __f1(self):  # _Foo__f1
        print('from test')


print(Foo.__dict__)
print(Foo._Foo__x)
print(Foo._Foo__f1)

II: This hidden within the external wrong, because properties will begin with __ uniform deformation occurs when the body type checking code syntax


class Foo:
    __x = 1  # _Foo__x = 1

    def __f1(self):  # _Foo__f1
        print('from test')

    def f2(self):
        print(self.__x) # print(self._Foo__x)
        print(self.__f1) # print(self._Foo__f1)

print(Foo.__x)
print(Foo.__f1)
obj=Foo()
obj.f2()

III: This deforming operation only occurs when the grammar checking a class member, __ after the beginning of the attribute definitions are not deformed


class Foo:
    __x = 1  # _Foo__x = 1

    def __f1(self):  # _Foo__f1
        print('from test')

    def f2(self):
        print(self.__x) # print(self._Foo__x)
        print(self.__f1) # print(self._Foo__f1)

Foo.__y=3
print(Foo.__dict__)
print(Foo.__y)

class Foo:
    __x = 1  # _Foo__x = 1

    def __init__(self,name,age):
        self.__name=name
        self.__age=age

obj=Foo('egon',18)
print(obj.__dict__)
print(obj.name,obj.age)

2, why hide?
I, hidden data attribute "hidden data class limits direct external operation on the data, then the interface should provide class permitted operation data outside indirectly,
on the interface may additionally additional logic to the data operating strictly controlled:
designer:


class People:
    def __init__(self, name):
        self.__name = name

    def get_name(self):
        # 通过该接口就可以间接地访问到名字属性
        # print('不让看')
        print(self.__name)

    def set_name(self,val):
        if type(val) is not str:
            print('必须传字符串类型')
            return
        self.__name=val

User:
obj = People ( 'Egon')
Print (obj.name) # Name property can not be directly
obj.set_name ( 'EGON')
obj.set_name (123123123)
obj.get_name ()
II, hiding function / method attributes: purpose is to isolate the complexity

Guess you like

Origin www.cnblogs.com/Franciszw/p/12664123.html