Python面向对象之类和实例用法分析
作者:feesland 发布时间:2022-09-09 00:02:33
本文实例讲述了Python面向对象之类和实例用法。分享给大家供大家参考,具体如下:
类
虽然 Python 是解释性语言,但是它是面向对象的,能够进行对象编程。至于何为面向对象,在此就不详说了。面向对象程序设计本身就很值得深入学习,如要了解,请参阅网上其他的资料。
面向对象最重要的概念就是类(Class)和实例(Instance),牢记 类 是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。
以Student类为例,在Python中,定义类是通过 class
关键字:
注意:Python 2.X 需要在类名后面加 (object) 这边 pass 语句表示空语句段。
class 后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。
class Student(object):
pass
Python 3.X 则只需要类名,不需要加 (object)
class Student:
pass
实例
创建实例是通过类名+()实现的(若 __init__ 无或仅有self);如定义好了Student类,就可以根据Student类创建出Student的实例,如下:
class Student(object):
pass
May = Student() # 新建May实例
print(May)
运行结果:
<__main__.Student object at 0x0000000001DCC400>
可以看到,变量May指向的就是一个Student的object,后面的0x006C4770是内存地址,每个object的地址都不一样,而Student本身则是一个类。
可以自由地给一个实例变量绑定属性,比如,给实例 May 绑定一个 name 属性,这个 name 属性是实例 May 特有的,其他新建的实例是没有 name 属性的
class Student(object):
pass
May = Student() # 新建May实例
print(May)
May.name = "May" # 给实例 May 绑定 name 属性为 "May"
print(May.name)
Peter = Student() # 新建Peter实例
# print(Peter.name) # 报错,因为Peter没有Name属性
那么,如果我们需要类必须绑定属性,那如何定义呢? 请参见下文。
__init__ 构造函数
由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。 (注意 __init__
双下划线)
如对于Student类,我们定义 name 和 score 属性(所有Sudent 都须有的属性):
__init__
方法的第一个参数永远是self
,表示创建的实例本身,因此,在__init__
方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。
有了__init__
方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__
方法匹配的参数,但self
不需要传,Python解释器自己会把实例变量传进去:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
May = Student("May",90) # 须要提供两个属性
Peter = Student("Peter",85)
print(May.name, May.score)
print(Peter.name, Peter.score)
__del__ 析构函数
Just like the __init__ method, there is another special method __del__ which is called when an object is going to die i.e. it is no longer being used and is being returned to the computer system for reusing that piece of memory.
The __del__ method is run when the object is no longer in use and there is no guarantee when that method will be run. If you want to explicitly see it in action, we have to use the del statement which is what we have done here.
相对于 构造函数 Python 也有类似 C++ 中的析构函数 __del__
, Python的垃圾回收过程与常用语言的不一样,如果一定需要,最好需要使用del语句来激活。
私有变量
Note for C++/Java/C# Programmers
All class members (including the data members) are public and all the methods are virtual in Python.
One exception: If you use data members with names using the double underscore prefix such as __privatevar, Python uses name-mangling to effectively make it a private variable.
Thus, the convention followed is that any variable that is to be used only within the class or object should begin with an underscore and all other names are public and can be used by other classes/objects. Remember that this is only a convention and is not enforced by Python (except for the double underscore prefix).
Python 中定义私有变量,命名规则为前缀加两个下划线 “__” ,注意不可前后都包含__XXX__(该命名表示为类属性或内建变量);还有一种命名为单下划线 _XXX ,表示约定俗成不可访问的变量。
class Person(object):
def __init__(self,name,sex):
self.name = name
self.__sex = sex # sex 定义为私有变量
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
May = Person("May","female")
print(May.name)
print(May.__sex) # 会报错
希望本文所述对大家Python程序设计有所帮助。
来源:https://www.cnblogs.com/feeland/p/4409130.html
猜你喜欢
- 首先创建scrapy项目命令:scrapy startproject douban_read创建spider命令:scrapy genspi
- WebDriver简介selenium从2.0开始集成了webdriver的API,提供了更简单,更简洁的编程接口。selenium web
- 如何在页面中快捷地添加翻页按钮? 先编写一个nextprev.inc文件,再将代码<
- 本文使用python的第三方模块requests爬取王者荣耀所有英雄的图片,并将图片按每个英雄为一个目录存入文件夹中,方便用作桌面壁纸下面时
- 本文实例讲述了Python爬虫爬取杭州24时温度并展示操作。分享给大家供大家参考,具体如下:散点图 爬虫杭州今日24时温度 https://
- # -*- encoding: utf8 -*-import osimport sysimport ftplibclass FTPSync(
- 一般上电子商务网站买东西的用户分三种:随便看看,就是不买先看看,买不买再说就是来买东西的这样的需求反应到产品页的购买按钮上,我们一般会看到购
- Page Object模式是Selenium中的一种测试设计模式,主要是将每一个页面设计为一个Class,其中包含页面中需要测
- 打包下载Pain.php <?php class Pain { public $var=array(); public $tpl=ar
- 1、fit和fit_generator的区别首先Keras中的fit()函数传入的x_train和y_train是被完整的加载进内存的,当然
- 感觉上次写的植物大战僵尸与俄罗斯方块的反应还不错,这次这个文章就更有动力了这次就写一个天天酷跑吧写出来的效果图就是这样了下面就更新一下全部的
- 今天介绍一种基于高斯滤波和邻域随机采样,生成一种毛玻璃的图像特效,简单来说,就是先对图像做高斯滤波模糊,然后对模糊后的图像,通过对邻域的随机
- websocket网易聊天室?web微信?直播?假如你工作以后,你的老板让你来开发一个内部的微信程序,你需要怎么办?我们先来分析一下里面的技
- 想实现发送邮件需要经过以下几步:1、登录邮件服务器2、构造符合邮件协议规则要求的邮件内容3、发送Python对SMTP支持有smtplib和
- 一、题目内容给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的
- 一、当我们用Python matplot时作图时,一些数据需要以百分比显示,以更方便地对比模型的性能提升百分比。二、借助matplotlib
- 光的干涉干涉即两束光在叠加过程中出现的强度周期性变化情况,其最简单的案例即为杨氏双缝干涉。如图所示,光从 S S S点发出,通过两个狭缝 S
- 本文实例讲述了python使用arp欺骗伪造网关的方法。分享给大家供大家参考。具体实现方法如下:#coding:utf-8''
- 前端使用ajax进行数据交互时:$.ajax({ cache: false, type: "POST", url: {%
- 使用pandas读取xml文件报错“ Unsupported format, or corrupt file: Expected BOF r