cook book 类与对象 1

pipidi

zhujingdi1998@gmail.com

python 类与对象

使用 with 语句

在__enter__时候开始服务 __exit__时候关闭服务 可以用在写数据库连接的时候 或者是那些需要关闭的文件等

from socket import socket, AF_INET, SOCK_STREAM
from functools import partial


class LazyConnection:
    def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
        self.address = address
        self.family = family
        self.type = type
        # self.sock = None
        self.connection=[]
    def __enter__(self):

        self.sock = socket(self.family, self.type)
        self.sock.connect(self.address)
        self.connection.append(self.sock)
        return self.sock

    def __exit__(self, exc_ty, exc_val, tb):
        self.connection.pop().close()


conn = LazyConnection(('www.python.org', 80))
# Connection closed
with conn as s:
    # conn.__enter__() executes: connection open
    pass
    with conn as s2:
        pass

python 类与对象的 保护属性和私有属性

class B:
    def __init__(self):

        self.__private=0

    def __private_method(self):
        print(1)

    def a(self):
        self.__private_method()
class C(B):
    def __init__(self):
        super().__init__()
        self.__private=1



    # can't override B.__private_method

    def b(self):
        self.__private_method()

C().b()
#Traceback (most recent call last):
 # File "C:/Users/战神皮皮迪/PycharmProjects/cookbook/ClassAndInstance/encapsulate_name_to_class.py", line 33, in <module>
    C().b()
 # File "C:/Users/战神皮皮迪/PycharmProjects/cookbook/ClassAndInstance/encapsulate_name_to_class.py", line 30, in b
    self.__private_method()
#AttributeError: 'C' object has no attribute '_C__private_method'

使用双下划线的无法继承 属于内部实现的 如果试图重写这个方法 这个方法就回变成_C__private_method 与父类的方法是完全不同的

阅读量