1. 程式人生 > 實用技巧 >組合/多型/反射/內建方法/ 套接字程式設計/繫結方法與非繫結方法

組合/多型/反射/內建方法/ 套接字程式設計/繫結方法與非繫結方法

一、組合

# 組合與繼承都是為了解決類與類直接冗餘問題的
# 繼承: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()


# obj1\obj2\obj3三者都是動物
# 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=》標識全世界範圍內獨一無二的一個基於網路通訊的應用軟體