python基础学习18----面向对象简述

这里就不再讲面向对象的相关概念知识或者与面向过程的比较了,直接进入类的学习

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self):#构造<a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>
    pass

sfencs=people()#类的实例

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,name,age):
    self.name=name
    self.age=age

sfencs=people("sfencs",19)
print("%s is %d"%(sfencs.name,sfencs.age))

Highlighter">
rush:python;gutter:true;">class father:
    def __init__(self):
        self.a = 1
        self.b = 2
def me(self):
    print("i am father")
    print(self)#<__main__.son object at 0x000001F7DFA11128>

class son(father):

def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self):
    <a href="https://www.jb51.cc/tag/super/" target="_blank" class="keywords">super()</a>.<a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__()</a>
    super(son,self).me()#执行<a href="https://www.jb51.cc/tag/fulei/" target="_blank" class="keywords">父类</a>的me<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>,但self是people

def me(self):
    print("i am son")

people=son()
print(people.a)#1
people.me()#i am son

子类可以对父类方法进行重写,子类调用父类方法使用super(子类名,self),self永远是执行该方法调用

python支持多继承

Highlighter">
rush:python;gutter:true;">class father1:
    def __init__(self):
        self.a = 1
        self.b = 2
def me(self):
    print("i am father1")

class father2:
def init(self):
self.c = 3
self.d = 4

def me(self):
    print("i am father2")

class son(father1,father2):

def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self):
    father1.<a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self)
    father2.<a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self)
    super(son,self).me()#i am father1

def me(self):
    print("i am son")

people=son()
print(people.c)#3
people.me()#i am son

多继承中子类调用父类方法的寻找方法是按照父类声明的顺序从左到右,从下到上查找,一直查找到最高级的父类,但是如果不同的父类继承于同一个父类

那么这个相当于根的父类为最后再去查找

python原生多态,不像java,c++那样必须在方法的形参处申明类型

方法

sex="male"为静态字段,可以通过对象访问 也可以通过类访问

self.name=name    self.age=age

Highlighter">
rush:python;gutter:true;">class people:
sex="male"
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,"19")

print(sfencs.name)
print(sfencs.sex)
print(people.sex)

静态方法可以通过对象访问 也可以通过类访问,声明静态方法的方式为@staticmethod

Highlighter">
rush:python;gutter:true;">class people:
sex="male"
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age
@stati<a href="https://www.jb51.cc/tag/cme/" target="_blank" class="keywords">cme</a>thod
def func():
    print("这是静态<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>")

sfencs=people("sfencs","19")
sfencs.func()
people.func()

方法也可以通过对象访问 也可以通过类访问,声明类方法的方式为@classmethod,类方法的参数为类

Highlighter">
rush:python;gutter:true;">class people:
sex="male"
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age
@classmethod
def func(cls):
    print("这是类<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>")
    print(cls)#<class '__main__.people'>

sfencs=people("sfencs","19")
sfencs.func()
people.func()

属性

属性定义的时候像方法,使用的时候像字段,使用@property声明,这样就可以使sfencs.func有对应的值

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age
@property
def func(self):
    return 1

sfencs=people("sfencs","19")
print(sfencs.func)#1

既然要伪装成字段,那么不仅仅是能够有对应的值,也应该能够为它赋值,将它删除等操作

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age
@property
def func(self):
    return 1
@func.setter
def func(self,val):
    print(val)

@func.deleter
def func(self):
    print("del")

sfencs=people("sfencs","19")
print(sfencs.func)#1
sfencs.func=123
del sfencs.func

 @func.setter为设置赋值的方法,@func.deleter为删除设置的方法

经过这些设置之后,看似func成立一个字段,有了相应的特点,但其实这些特点都是假的。这三种方式只是3中对应关系,只是使用时是模仿字段操作,但真实操作是由

自己规定的,del并不能真的删除,而只是按照你所写的方法做相应的动作。

除此之外属性还有一种设置方式

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age

def f1(self):
    return 1

def f2(self,val):
    print(val)

def f3(self):
    print("del")

func=property(<a href="https://www.jb51.cc/tag/fget/" target="_blank" class="keywords">fget</a>=f1,fset=f2,fdel=f3,doc="描述")

sfencs=people("sfencs","19")
print(sfencs.func)#1
sfencs.func=123
del sfencs.func

只是方式改变了,效果还一样,不多说了。

这里就指将成员声明为私有的

Highlighter">
class people:    def __init__(self,age):        self.name=name        self.__age=age    def getage(self):        return self.__agesfencs=people("sfencs","19")#print(sfencs.__age)私有成员不能直接通过对象来拿print(sfencs.getage())#19

当然也有私有方法

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.__age=age
def getage(self):
    return self.__age
def __fun(self):
    print("这是私有<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a>")
def func(self):
    self.__fun()

sfencs=people("sfencs","19")

print(sfencs.__age)私有成员不能直接通过对象来拿

print(sfencs.getage())

sfencs.__fun()

sfencs.func()

在继承当中,私有成员与方法是不能被子类继承的

方法

__init__

构造方法,这个不用过多解释

__del__

析构方法,当对象在内存中被释放时,自动触发执行

Highlighter">
rush:python;gutter:true;">def __del__(self):
    pass

__call__

对象后面加括号,触发执行

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.__age=age

def __call__(self,a,b):
    print("__call__")
    print(a,b)

sfencs=people("sfencs",19)
sfencs(1,2)

__int__

调用int(对象)时使用的方法

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.__age=age

def __int__(self):
    return 10

sfencs=people("sfencs",19)
data=int(sfencs)
print(data)#10

__str__

那么在打印 对象 时,输出方法的返回值

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.__age=age

def __str__(self):
    return "hello world"

sfencs=people("sfencs",19)
print(sfencs)#hello world

__add__

两个对象相加执行该方法

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age

def __add__(self,other):
    return self.age+other.age

sfencs=people("sfencs",19)
Tom=people("Tom",20)
print(sfencs+Tom)#39

__dict__  

查看类或对象中的所有成员

Highlighter">
rush:python;gutter:true;">class people:
sex="male"
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age

sfencs=people("sfencs",19)
print(sfencs.dict)#{'name': 'sfencs','age': 19}
print(people.dict)

{'module': 'main','sex': 'male','init': <function people.init at 0x000001B6C6F2C2F0>,'dict': <attribute 'dict' of 'people' objects>,'weakref': <attribute 'weakref' of 'people' objects>,'doc': None}

__getitem__、__setitem__、__delitem__

用于索引操作,如字典。以上分别表示获取、设置、删除数据

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,age):
    self.name=name
    self.age=age

def __getitem__(self,key):
    print('__getitem__',key)
    return 2

def __setitem__(self,key,value):
    print('__setitem__',value)

def __delitem__(self,key):
    print('__delitem__',key)

sfencs=people("sfencs",19)
sfencs["one"]=1#setitem one 1
print(sfencs["one"])#getitem one 2
del sfencs["one"]#delitem one

__iter__

之所以列表、字典、元组可以进行for循环,是因为类型内部定义了 __iter__
Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,list):
    self.list=list

def __iter__(self):
    return iter(self.list)

sfencs=people([1,2,3,4,5])

for i in sfencs:
print(i)

__module__ 和  __class__

表示当前操作的对象在那个模块

表示当前操作的对象的类是什么
Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,19)

print(sfencs.module)#main
print(sfencs.class)#<class 'main.people'>

Highlighter">
rush:python;gutter:true;">def f(self):
    print(self.name,self.age)

def init(self,age):
self.name = name
self.age = age

people = type('people',(object,),{'func':f,'init':init})

sfencs=people("sfencs",19)
sfencs.func()

这种方式可以看出,类也是一种对象,是type类型的对象

我们可以从下面这张图看出类的实际创建过程

反射可以通过字符串的方式来找到对象中的变量或方法

反射有4个方法getattr() hasattr() setattr() delattr()

Highlighter">
rush:python;gutter:true;">class people:
def <a href="https://www.jb51.cc/tag/init/" target="_blank" class="keywords">__init__</a>(self,19)

data1=getattr(sfencs,"name")
print(data1)#sfencs
data2=hasattr(sfencs,"age")
print(data2)#True
setattr(sfencs,"age",20)
print(sfencs.age)#20
delattr(sfencs,"age")
data3=hasattr(sfencs,"age")
print(data3)#False

python一切事物皆是对象,模块同样也支持反射来操作

对象也叫实例,单例模式表示该类只有一个对象

Highlighter">
rush:python;gutter:true;">class ConnectPool:
    __instatnce=None
    @staticmethod
    def get_instance():
        if ConnectPool.__instatnce:
            return ConnectPool.__instatnce
        else:
            ConnectPool.__instatnce = ConnectPool()
            return ConnectPool.__instatnce

obj =ConnectPool.get_instance()
print(obj)#<main.ConnectPool object at 0x000002523F0174E0>
obj1 =ConnectPool.get_instance()
print(obj1)#<main.ConnectPool object at 0x000002523F0174E0>
print(obj1==obj)#True

   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic violinplot2. 小提琴图样式自定义 Custom seaborn violinplot3. 小提琴图颜色自定义 Control color of seaborn violinplot4. 分组小提琴图 Group
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic density plot2. 核密度图的区间控制 Control bandwidth of density plot3. 多个变量的核密度图绘制 Density plot of several variables4. 边
首先 import tensorflow as tf tf.argmax(tenso,n)函数会返回tensor中参数指定的维度中的最大值的索引或者向量。当tensor为矩阵返回向量,tensor为向量返回索引号。其中n表示具体参数的维度。 以实际例子为说明: import tensorflow a
seaborn学习笔记章节 seaborn是一个基于matplotlib的Python数据可视化库。seaborn是matplotlib的高级封装,可以绘制有吸引力且信息丰富的统计图形。相对于matplotlib,seaborn语法更简洁,两者关系类似于numpy和pandas之间的关系,seabo
Python ConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。 文章目录 1 介绍1.1 Python ConfigParser读取文件1.2 Python ConfigParser中的节1.3 Python ConfigParser从字符串中读取数据
1. 处理Excel 电子表格笔记(第12章)(代码下载) 本文主要介绍openpyxl 的2.5.12版处理excel电子表格,原书是2.1.4 版,OpenPyXL 团队会经常发布新版本。不过不用担心,新版本应该在相当长的时间内向后兼容。如果你有新版本,想看看它提供了什么新功能,可以查看Open
1. 发送电子邮件和短信笔记(第16章)(代码下载) 1.1 发送电子邮件 简单邮件传输协议(SMTP)是用于发送电子邮件的协议。SMTP 规定电子邮件应该如何格式化、加密、在邮件服务器之间传递,以及在你点击发送后,计算机要处理的所有其他细节。。但是,你并不需要知道这些技术细节,因为Python 的
文章目录 12 绘图实例(4) Drawing example(4)1. Scatterplot with varying point sizes and hues(relplot)2. Scatterplot with categorical variables(swarmplot)3. Scat
文章目录 10 绘图实例(2) Drawing example(2)1. Grouped violinplots with split violins(violinplot)2. Annotated heatmaps(heatmap)3. Hexbin plot with marginal dist
文章目录 9 绘图实例(1) Drawing example(1)1. Anscombe’s quartet(lmplot)2. Color palette choices(barplot)3. Different cubehelix palettes(kdeplot)4. Distribution
Python装饰器教程展示了如何在Python中使用装饰器基本功能。 文章目录 1 使用教程1.1 Python装饰器简单示例1.2 带@符号的Python装饰器1.3 用参数修饰函数1.4 Python装饰器修改数据1.5 Python多层装饰器1.6 Python装饰器计时示例 2 参考 1 使
1. 用GUI 自动化控制键盘和鼠标第18章 (代码下载) pyautogui模块可以向Windows、OS X 和Linux 发送虚拟按键和鼠标点击。根据使用的操作系统,在安装pyautogui之前,可能需要安装一些其他模块。 Windows: 不需要安装其他模块。OS X: sudo pip3
文章目录 生成文件目录结构多图合并找出文件夹中相似图像 生成文件目录结构 生成文件夹或文件的目录结构,并保存结果。可选是否滤除目录,特定文件以及可以设定最大查找文件结构深度。效果如下: root:[z:/] |--a.py |--image | |--cat1.jpg | |--cat2.jpg |
文章目录 VENN DIAGRAM(维恩图)1. 具有2个分组的基本的维恩图 Venn diagram with 2 groups2. 具有3个组的基本维恩图 Venn diagram with 3 groups3. 自定义维恩图 Custom Venn diagram4. 精致的维恩图 Elabo
mxnet60分钟入门Gluon教程代码下载,适合做过深度学习的人使用。入门教程地址: https://beta.mxnet.io/guide/getting-started/crash-course/index.html mxnet安装方法:pip install mxnet 1 在mxnet中使
文章目录 1 安装2 快速入门2.1 基本用法2.2 输出图像格式2.3 图像style设置2.4 属性2.5 子图和聚类 3 实例4 如何进一步使用python graphviz Graphviz是一款能够自动排版的流程图绘图软件。python graphviz则是graphviz的python实