组合/多态/反射/内置方法/ 套接字编程/绑定方法与非绑定方法

一、组合

# 组合与继承都是为了解决类与类直接冗余问题的
# 继承:is-a
# 组合:has-a

class People:
    school = "oldboy"

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

class CourseMixin:
    def tell_courses_info(self):
        print("============%s==========" %self.name)
        for course_obj in self.courses:
            course_obj.tell_info()


class Student(CourseMixin,People):
    def __init__(self, name, age, gender, stu_id):
        People.__init__(self, name, age, gender)

        self.stu_id = stu_id
        self.courses = []

    def choose(self):
        pass


class Teacher(CourseMixin,People):
    def __init__(self, name, age, gender, level, salary):
        People.__init__(self, name, age, gender)

        self.level = level
        self.salary = salary
        self.courses = []

    def score(self):
        pass


class Course:
    def __init__(self, name, price, period):
        self.name = name
        self.price = price
        self.period = period

    def tell_info(self):
        print("<名字:%s> <价钱:%s> <周期:%s>" %(self.name,self.price,self.period))


stu = Student('张三', 18, 'male', 33, )
tea = Teacher("egon", 18, 'male', 10, 3000)
python_obj = Course("python", 33000, "6mons")
linux_obj = Course("linux", 20000, "5mons")

stu.courses.append(python_obj)
stu.courses.append(linux_obj)

tea.courses.append(python_obj)

# print(stu.courses)
# print(tea.courses)

# print(stu.courses[0])


stu.tell_courses_info()
tea.tell_courses_info()
示例练习

二、多态

# 多态: 同一种事物有多种形态
# 多态性:指的是我们可以在不考虑对象具体类型的前提下,而直接使用对象
# 多态性=》归一化设计
import abc


class Animal(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def speak(self):
        pass

# Animal()  # Animal变成了一个模板类,不能实例化得到对象

class People(Animal):
    def speak(self):
        # print("啊啊啊啊")
        pass
    # pass

class Dog(Animal):
    def speak(self):
        print('汪汪汪')


class Pig(Animal):
    def speak(self):
        print('哼哼哼')


obj1 = People()
obj2 = Dog()
obj3 = Pig()


# obj1obj2obj3三者都是动物
# obj1.speak()
# obj2.speak()
# obj3.speak()

# def speak(animal):
#     animal.speak()
#
#
# speak(obj1)
# speak(obj2)
# speak(obj3)

# len("hello")  # "hello".__len__
# len([1,2,3])  # [1,2,3].__len__
# len((1,2,3))  # (1,2,3).__len__


# python推崇鸭子类型
class People:
    def speak(self):
        # print("啊啊啊啊")
        pass
    # pass

class Dog:
    def speak(self):
        print('汪汪汪')


class Pig:
    def speak(self):
        print('哼哼哼')


obj1 = People()
obj2 = Dog()
obj3 = Pig()
示例练习

三、绑定方法与非绑定方法

1、绑定方法
# 特殊之处:与调用者捆绑,应该由捆绑的调用者里调用,调用者在调用时会将自身当作第一个参数传入
# 1.1 绑定给对象的方法:类中定义的函数默认都是绑定给对象的,应该由对象来调用,会对象自己当作第一个参数传入
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def tell_info(self):
        print("<%s:%s>" %(self.name, self.age))

obj = People("egon",18)
obj.tell_info()

  # 1.2 绑定给类的方法:在类中定义的函数上添加装饰器classmethod,应该由类来调用,会类自己当作第一个参数传入

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

    def tell_info(self):
        print("<%s:%s>" %(self.name, self.age))

    @classmethod
    def f1(cls):
        print(cls)

obj = People("egon",18)
obj.tell_info()

print(People.tell_info)
print(People.f1)
People.tell_info()

People.f1()

 # 2、非绑定方法

# 特殊之处:不予任何人捆绑,谁都可以来调用,就是一个普通函数,没有自动传参的效果
# 非绑定方法:在类中定义的函数上添加装饰器staticmethod,谁都可以来调用,就是一个普通函数,没有自动传参的效果
class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def tell_info(self):
        print("<%s:%s>" %(self.name, self.age))

    @classmethod
    def f1(cls):
        print(cls)

    @staticmethod
    def f2(x,y):
        print(x,y)


obj=People('egon',18)

# print(People.f2)
# print(obj.f2)

People.f2(1,2)
obj.f2(3,4)

  #3 .应用场景

import settings
import uuid

class Mysql:
    def __init__(self, ip, port):
        self.id = self.create_id()
        self.ip = ip
        self.port = port

    def tell_info(self):
        print("<%s:%s>" % (self.ip, self.port))

    @classmethod
    def from_conf(cls):
        return cls(settings.IP, settings.PORT)

    @staticmethod
    def create_id():
        return uuid.uuid4()

obj1 = Mysql('172.168.10.11', 3030)

# obj2 = Mysql.from_conf()
# print(obj2.__dict__)

# print(Mysql.create_id())
# print(obj2.create_id())
示例练习

四、反射

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


obj = People("egon")

# res = hasattr(obj, "name")  # "name" in obj.__dict__
# print(res)

# res = getattr(obj, "name")  # obj.name
# print(res)

# setattr(obj,"name","EGON")  # obj.name="EGON"
# print(obj.name)

# delattr(obj,"name")
# print(obj.__dict__)

# print(hasattr(People,"x"))

class Ftp:
    def get(self):
        print('get...')

    def put(self):
        print('put...')


obj=Ftp()
cmd=input('>>>: ')  # get
if hasattr(obj,cmd):
    f=getattr(obj,cmd)
    print(f)
    f()
示例

五、内置方法

# __方法__:称之为内置方法,定义在类内部,都不是直接调用的,都是在满足某种条件下自动触发执行的

1.__str__:在打印对象时自动触发执行,将返回值当作打印的结果输出,注意返回值必须是字符串类型
class People:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def __str__(self):
        return "<%s:%s:%s>" %(self.name,self.age,self.gender)

obj = People("egon",18,'male')
print(obj)  # print(obj.__str__())
len(obj)  # obj.__len__


l=[111,222,333]  # l=list([111,222,333])
print(l)

x=10 # x=int(10)
print(x)
示例练习

2.__del__:删除对象内存空间之前,自动触发执行,用于回收操作系统资源

class Bar:
    pass

class Foo(Bar):
    def __init__(self, x, y,filepath):
        self.x = x
        self.y = y
        self.f=open(filepath,mode='r',encoding='utf-8')

    # def __del__(self):
    #     print('回收系统资源的代码')
    #     self.f.close()

obj=Foo(111,222,'a.txt')
# del obj
# print('============main===============')


print(isinstance(obj,Foo))
print(isinstance(10,int))

print(issubclass(Foo,Bar))
示例练习

六、套接字编程

C/S架构
client--------互联网--------server

B/S
browser--------互联网--------server

服务端:
1、一直对外提供服务
2、服务端的必须绑定一个固定的地址
3、并发能力

网络存在的意义?
互联网存在的意义让通信变得方便

什么是互联网?
网络=底层物理连接介质+互联网通信协议


ip+mac=》标识全世界范围内独一无二的一台计算机
ip+mac+port=》标识全世界范围内独一无二的一个基于网络通信的应用软件

因为ARP协议的存在,可以将ip解析成mac,所以:
ip+port=》标识全世界范围内独一无二的一个基于网络通信的应用软件
原文地址:https://www.cnblogs.com/datatool/p/13657336.html