zl程序教程

您现在的位置是:首页 >  后端

当前栏目

编程语言之 Python入门到精通.(基本知识:类与对象,特殊的方法,类的浅拷贝与深拷贝,模块等.)

2023-09-27 14:29:29 时间

Python语言的概括

Python 是一门 非常简单容易好学的编程语言,同时也有比较强大的功能,具有一定的丰富和强大库,开发效率特别高。Python 常被昵称为胶水语言,能够把用其他语言制作的各种模块(比如:C语言和C++)很轻松的联结在一起.(Python:也是一门面向对象的解释型编程语言,Python 语法简洁清晰优雅,特色之一是强制用空白符(white space)作为语句缩进.

目录

Python代码的理解:

类与对象:

(1)类的创建:

(2)类的对象创建:

(3)类属性,类方法,静态方法的使用:

(4)动态绑定属性和方法:

(5)知识点总结:

封装:

继承:

方法重写:

object类:

多态:

特殊属性:

特殊的方法:

类的浅拷贝与深拷贝:

(1)浅拷贝:

(2)深拷贝:

(3)知识总结:

什么叫模块:

(1)创建模块:

(2)导入模块:

(3)导入自定义的模块:

(4)calc模块(自定义的):

(5)cty模块调用了calc模块(自定义的):

(6)以主程形式运行:

(7)calc2模块:

(8)cty模块:


Python 特点:

(1)容易学习:Python 相对于其他语言有较少的关键字,结构简单和一个明确定义的语法,学习起来比较简单一点.

(2)容易阅读:Python代码定义的是比较清晰.

(3)容易维护:Python的源代码是相当容易维护一点.

(4)有一个广泛的标准库:Python的最大的优势之一是有一个非常丰富的库,可以跨平台,在UNIX,Windows和Macintosh兼容性比较好.

(5)有互动模式:有互动模式的支持,可以从终端输入执行代码并获得结果的语言,互动的测试和调试代码片断.

(6)可以移植:有开放源代码的特性,Python已经被移植(也就是使其工作)到许多平台上.

(7)可以扩展:假如你需要一段运行关键代码,或者是想要编写一些不愿开放的算法,你可以使用C或C++完成那部分程序,最后在你的Python程序中调用.

(8)数据库:Python可以提供主要的商业数据库的接口.

(9)GUI编程:Python支持GUI也可以创建和移植到许多系统调用.

(10)可嵌入: 你可以将Python嵌入到C/C++程序中,可以让你的程序的用户获得"脚本化"的能力. 


知识点 上一页:

Python代码理解的 前面知识(上一页)编程语言之 Python入门到精通.(基本知识:函数,Bug的由来及分类,异常处理机制等.)
    


Python代码的理解:

类与对象:

类就是数据类型:
对象就是类型中不同的值:


(1)类的创建:

class Svtudent:
    native_place='hhh'      #类的属性
    def __init__(self,name,age):            #name,age为实例属性
        self.name=name
        self.age=age
    #实例方法
    def info(self):
        print ('我的名字叫:',self.name,'年龄是:',self.age)

    #类方法
    @classmethod
    def cm(cls):
        print ('类方法')

    #静态方法:
    @staticmethod
    def sm():
        print ('静态方法')

(2)类的对象创建:

class Svtudent:
    native_place='hhh'      #类的属性
    def __init__(self,name,age):            #name,age为实例属性
        self.name=name
        self.age=age
    #实例方法
    def info(self):
        print ('我的名字叫:',self.name,'年龄是:',self.age)

    #类方法
    @classmethod
    def cm(cls):
        print ('类方法')

    #静态方法:
    @staticmethod
    def sm():
        print ('静态方法')

#类的对象创建:
sl=Svtudent('张三',188888)
sl.cm()				#
sl.info()				#
print (sl.name)			#
print (sl.age)			#

#输出的结果:类方法
#输出的结果:我的名字叫: 张三 年龄是: 188888
#输出的结果:张三
#输出的结果:188888

(3)类属性,类方法,静态方法的使用:

class Svtudent:
    native_place='广州'      #类的属性
    def __init__(self,name,age):            #name,age为实例属性
        self.name=name
        self.age=age
    #实例方法
    def info(self):
        print ('我的名字叫:',self.name,'年龄是:',self.age)

    #类方法
    @classmethod
    def lff(cls):
        print ('类方法')

    #静态方法:
    @staticmethod
    def jtff():
        print ('静态方法')

print (Svtudent.native_place)
ss=Svtudent('张三',30)                        #给Svtudent类赋值
ee=Svtudent('李四',60)                        #给Svtudent类赋值
Svtudent.native_place='嘿嘿嘿!'                #覆盖上面的类的属性
print (Svtudent.native_place)
print (ss.age)
print (ee.name)

Svtudent.lff()                  #可以直接使用类方法
Svtudent.jtff()                 #可以直接使用静态方法

#输出的结果:广州
#输出的结果:嘿嘿嘿!
#输出的结果:30
#输出的结果:李四
#输出的结果:类方法
#输出的结果:静态方法

(4)动态绑定属性和方法:

class Svtudent:
    native_place='广州'      #类的属性
    def __init__(self,name,age):            #name,age为实例属性
        self.name=name
        self.age=age
    #实例方法
    def info(self):
        print ('我的名字叫:',self.name,'年龄是:',self.age)

    #类方法
    @classmethod
    def lff(cls):
        print ('类方法')

    #静态方法:
    @staticmethod
    def jtff():
        print ('静态方法')

ss=Svtudent('张三',30)                        #给Svtudent类赋值
ee=Svtudent('李四',60)                        #给Svtudent类赋值

ss.qq='男'					#动态绑定
ee.qq='女'					#动态绑定
print (ss.name,ss.age,ss.qq)
print (ee.name,ss.age,ss.qq)

def pp():					#函数
    print ('哈哈哈!')

ss.pp=pp()				#函数给了ss.pp就变方法
print (ss.pp)
ee.pp=pp()				#函数给了ee.pp就变方法
print (ee.pp)

#输出的结果:张三 30 男
#输出的结果:李四 30 男
#输出的结果:哈哈哈!
#输出的结果:None
#输出的结果:哈哈哈!
#输出的结果:None

(5)知识点总结:


封装:

class Student:
    def __init__(self,name,age):
        self.name=name
        self.__age=age
    def show(self):
        print (self.name,self.__age)
#输出的结果:张三 20


stn=Student('张三',20)
stn.show()

print (stn.name)
print (dir(stn))
print (stn._Student__age)

#输出的结果:张三
#输出的结果:['_Student__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'show']
#输出的结果:20

继承:

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print (self.name,self.age)

class Student(Person):
    def __init__(self,name,age,stu_no):
        super(Student, self).__init__(name,age)             #调用父类的方法
        self.stu_no=stu_no

class Teacher(Person):
    def __init__(self,name,age,teachofvear):
        super(Teacher, self).__init__(name,age)                 #调用父类的方法
        self.teachofvear=teachofvear

stu=Student('张三',20,'1001')
teacher=Teacher('hhh',30,'50')

stu.info()                                                  #info是继承的意思
teacher.info()                                              #info是继承的意思

#输出的结果:张三 20
#输出的结果:hhh 30

方法重写:

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def info(self):
        print (self.name,self.age)

class Student(Person):
    def __init__(self,name,age,stu_no):
        super(Student, self).__init__(name,age)             #调用父类的方法
        self.stu_no=stu_no
    def info(self):
        super(Student, self).info()                         #调用父类的方法
        print ('xx',self.stu_no)

class Teacher(Person):
    def __init__(self,name,age,teachofvear):
        super(Teacher, self).__init__(name,age)                 #调用父类的方法
        self.teachofvear=teachofvear
    def info(self):
        super(Teacher, self).info()                             #调用父类的方法
        print ('jiaon',self.teachofvear)

stu=Student('zhangsan',20,'1001')
teacher=Teacher('lisi',30,'10')
stu.info()                                                  #info是名字
teacher.info()                                              #info是名字


#输出的结果:zhangsan 20
#输出的结果:xx 1001
#输出的结果:lisi 30
#输出的结果:jiaon 10

object类:

class Student(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        print ('我的名字是{0},今年{1}年龄'.format(self.name,self.age))

stu=Student('张三',20)
print (stu)					#默认输出__str__

#输出的结果:我的名字是张三,今年20年龄

多态:

class Animal(object):
    def eat(self):
        print ('动物会吃')

class Dog(Animal):
    def eat(self):
        print ('狗吃肉')

class Cat(Animal):
    def eat(self):
        print ('猫吃鱼')

class Person():
    def eat(self):
        print ('人吃五谷杂粮')

def fun(obj):
    obj.eat()

fun(Cat())
fun(Dog())
fun(Animal())
fun(Person())

#输出的结果:猫吃鱼
#输出的结果:狗吃肉
#输出的结果:动物会吃
#输出的结果:人吃五谷杂粮

特殊属性:

class A:
    pass
class B:
    pass
class C(A,B):
    def __init__(self,name,age):
        self.name=name
        self.age=age

x=C('aaa',20)                   #x是C类型的一个实例对象

print (x.__dict__)              #实例对象的属性字典
print (x.__class__)             #输出对象的属类
print (C.__bases__)             #C类的父类类型关系

#输出的结果:{'name': 'aaa', 'age': 20}
#输出的结果:<class '__main__.C'>
#输出的结果:(<class '__main__.A'>, <class '__main__.B'>)

特殊的方法:

a=20
b=100
c=a+b
d=a.__add__(b)
print (c)
print (d)
#输出的结果:120
#输出的结果:120

class Student:
    def __init__(self,name):
        self.name=name
    def __add__(self, other):                       #__add__实现了两个对象可以相加
        return self.name+other.name

    def __len__(self):                              #__len__查看长度
        return len(self.name)

stu1=Student('张三')
stu2=Student('李四')

s=stu1+stu2
print (s)
#输出的结果:张三李四

f=stu1.__add__(stu2)
print (f)
#输出的结果:张三李四

lst=[11,22,33,44]
print (len(lst))
#输出的结果:4
print (lst.__len__())
#输出的结果:4
print (len(stu1))
#输出的结果:2

class Person(object):        #创建对象
    class Person(object):
        def __init__(self, name, age):
            slice.name = name
            self.age = age

    def __new__(cls, *args, **kwargs):              #对创建的对象进行初始化
        print ('__new__被调用执行了,cls的id值为{0}',format(id(cls)))
        #输出的结果:__new__被调用执行了,cls的id值为{0} 1751330296856

        obj=super(Person, cls).__new__(cls)
        print ('创建的对象的id为:{}'.format(id(obj)))
        #输出的结果:创建的对象的id为:1751336994744
        return obj

print ('object这个类对象的id为:{0}'.format(id(object)))
#输出的结果:__new__被调用执行了,cls的id值为{0} 3055270137080
print ('Person这个类对象的id为:{0}'.format(id(Person)))
#输出的结果:创建的对象的id为:3055277557688

p1=Person('张三',20)
print ('p1这个Person类的实例对象的id:{0}'.format(id(p1)))
#输出的结果:p1这个Person类的实例对象的id:2509557712824

类的浅拷贝与深拷贝:

class CPU:
    pass
class Disk:
    pass
class Computer:
    def __init__(self,cpu,disk):
        self.cpu=cpu
        self.disk=disk

cpu1=CPU()
cpu2=CPU()
print(cpu1,id(cpu1))
#输出的结果:<__main__.CPU object at 0x000001AF3ED3C7B8> 1852184971192
print (cpu2,id(cpu2))
#输出的结果:<__main__.CPU object at 0x000001AF3ED3C828> 1852184971304

(1)浅拷贝:

class CPU:
    pass
class Disk:
    pass
class Computer:
    def __init__(self,cpu,disk):
        self.cpu=cpu
        self.disk=disk

print ('lllllllllllllllllllllllllllllllllll')
pp=Computer('jjj',20)
print (pp.cpu,pp.disk)
#输出的结果:jjj 20


cpu1=CPU()
cpu2=CPU()
print(cpu1,id(cpu1))
#输出的结果:<__main__.CPU object at 0x0000028B277E10B8> 2796686282936
print (cpu2,id(cpu2))
#输出的结果:<__main__.CPU object at 0x00000287628A1470> 2780497056880

disk=Disk()
com=Computer(cpu1,Disk)

import copy                              #浅拷贝
ww=copy.copy(pp)                         #拷贝了pp的值.
print (pp,pp.disk,pp.cpu)
#输出的结果:<__main__.Computer object at 0x0000017FED2EC898> 20 jjj
print (ww,ww.disk,ww.cpu)
#输出的结果:<__main__.Computer object at 0x0000029552331518> 20 jjj

(2)深拷贝:

class CPU:
    pass
class Disk:
    pass
class Computer:
    def __init__(self,cpu,disk):
        self.cpu=cpu
        self.disk=disk

print ('lllllllllllllllllllllllllllllllllll')
pp=Computer('jjj',20)
print (pp.cpu,pp.disk)
#输出的结果:jjj 20


cpu1=CPU()
cpu2=CPU()
print(cpu1,id(cpu1))
#输出的结果:<__main__.CPU object at 0x0000028B277E10B8> 2796686282936
print (cpu2,id(cpu2))
#输出的结果:<__main__.CPU object at 0x00000287628A1470> 2780497056880

disk=Disk()
com=Computer(cpu1,Disk)

import copy                              #深拷贝
ww2=copy.deepcopy(pp)                      #拷贝了pp的值
print (pp,pp.disk,pp.cpu)
#输出的结果:<__main__.Computer object at 0x000001D79B00C898> 20 jjj
print (ww2,ww2.disk,ww2.cpu)
#输出的结果:<__main__.Computer object at 0x000001A1D2071550> 20 jjj

(3)知识总结:


什么叫模块:


(1)创建模块:


(2)导入模块:

#import模块名称 的模块导入		---导入模块中所以,模块中有什么就都可以使用.
import math     #关于数学运算
print (id(math))        #id
#输出的结果:2690848407448
print (type(math))      #类型
#输出的结果:<class 'module'>
print (math)            #值
#输出的结果:<module 'math' (built-in)>
print (math.pi)         #这个模块的中的值
#输出的结果:3.141592653589793
print ('-------------------------------')
print (dir(math))       #dir是查看这个模块中都有什么
#输出的结果:['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
print (math.tan(1))
#输出的结果:1.5574077246549023
print (math.pow(2,3),type(math.pow(2,3)))
#输出的结果:8.0 <class 'float'>
print (math.isnan(5))
#输出的结果:False
#From 模块名称 import 函数/变量/类  的模块导入	   --导入模块中的个数.
from math import pi,isnan,pow		#多个一起使用也是可以的
print (pi,isnan(5),pow(6,2))
#输出的结果:3.141592653589793 False 36.0
from math import pi
print (pi)
#输出的结果:3.141592653589793
from math import isnan
print (isnan(5))
#输出的结果:False
from math import pow
print (pow(2,3))
#输出的结果:8.0

(3)导入自定义的模块:


(4)calc模块(自定义的):

 

def add(a,b):
    c=a+b
    return c
def ff(a,b):
    c=b-a
    return c

(5)cty模块调用了calc模块(自定义的):

import calc
print (calc.add(10,20))
print (calc.ff(20,20))

(6)以主程形式运行:


(7)calc2模块:

def add(a,b):
    c=a+b
    return c

if __name__ == '__main__':				#不在别的模块中运行
    print (add(10,20))
#输出的结果:30

(8)cty模块:

import calc2
print (calc2.add(10,60))

Python代码理解的 后面知识(下一页):编程语言之 Python入门到精通.(综合知识:总结.)

    


参考链接:Python 简介 | 菜鸟教程

参考链接:什么是python?_技术是第一生产力-CSDN博客_什么是python

笔记学习于:花了2万多买的Python教程全套,现在分享给大家,入门到精通(Python全栈开发教程)_哔哩哔哩_bilibili