类的定义

class Student:

#定义类属性(类似于java的静态成员变量)

country = "China"

#构造函数

def __init__(self,name,score):#self代表对象本身,类似于java中的this

#声明成员变量

self._name = name#如果是一个_代表是私有变量(实际上仍然可以访问),两个下划线的时候__,编译器会自动更改变量名

self._score = score

#setter方法

def setName(self,name):

self._name = nameame

def setScore(self,score):

if score>0 and score <100:

self._score = score

#getter方法

def getName(self):

return self._name

def getScore(self):

return self._score

创建对象

stu = Student('kehao',80)

print(type(stu))

print(stu.getName())

stu.setScore(-10)

print(stu.getScore())

stu.setScore(90)

print(stu.getScore())

print(Student.country)

print(stu.country)

kehao

80

90

China

China

继承和多态

class Animal:

def run(self):

print('Animal is running...')

def sleep(self):

print('Sleeping')

class Dog(Animal):

#重载

def run(self):

print('Dog is running...')

def eat(self):

print('Eatting meats')

class Cat(Animal):

#重载

def run(self):

print('Cat is running...')

dog = Dog()

dog.run()

dog.sleep()

cat = Cat()

cat.run()

cat.sleep()

Dog is running...

Sleeping

Cat is running...

Sleeping

def run(animal):

animal.run()

animalList = [cat ,dog]

for animal in animalList:

run(animal)

Cat is running...

Dog is running...

一些常用的函数

isinstance(a, A)这个函数是看a是不是A的实例,子类对象对于父类也是返回True

type(a)返回a的类型

dir(a)获得a的所有方法和属性

getattr(obj,a,b):获取obj的a属性,如果没有则返回默认值b

setattr(obj,a,b):设置obj的a属性为b

hasattr(obj,a):判断obj是否有a 属性

print(isinstance(cat,Animal))#判断一个

print(isinstance('a',(int,float)))#判断多个

print(isinstance('a',(int,float,str)))

True

False

True

print(type(cat))

print(type(cat) == Cat)

#types里面有很多常量值

import types

if type(run) == types.FunctionType:

print('run is a function')

if type(abs) == types.BuiltinFunctionType:

print('abs is builtin function')

if type(lambda x:x*x) == types.LambdaType:

print("it's a lambda type")

if type((x for x in range(10)))==types.GeneratorType:

print("it is generate type")

True

run is a function

abs is builtin function

it's a lambda type

it is generate type

dir(stu) #返回一个列表,列表里是一个对象所有的属性和方法

['__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',

'_score',

'getName',

'getScore',

'setName',

'setScore']

限制实例的属性

使用__slots__

__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__

class Student(object):

__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称

s = Student() # 创建新的实例

s.name = 'Michael' # 绑定属性'name'

s.age = 25 # 绑定属性'age'

s.score = 99 # 绑定属性'score'

---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

in

----> 1 s.score = 99 # 绑定属性'score'

AttributeError: 'Student' object has no attribute 'score'

@property装饰器

负责把一个方法变成属性调用

getter和setter方法都为属性名

将getter方法上标注@property装饰器

将setter方法上标注函数名.setter装饰器

class Student1(object):

@property

def score(self):

return self._score

@score.setter

def score(self, value):

if not isinstance(value, int):

raise ValueError('score must be an integer!')

if value < 0 or value > 100:

raise ValueError('score must between 0 ~ 100!')

self._score = value

s = Student1()

s.score = 60 # OK,实际转化为s.set_score(60)

s.score # OK,实际转化为s.get_score()

60

s.score = 9999#报错是因为上面的函数抛出了错误

---------------------------------------------------------------------------

ValueError Traceback (most recent call last)

in

----> 1 s.score = 9999#报错是因为上面的函数抛出了错误

in score(self, value)

10 raise ValueError('score must be an integer!')

11 if value < 0 or value > 100:

---> 12 raise ValueError('score must between 0 ~ 100!')

13 self._score = value

ValueError: score must between 0 ~ 100!

多重继承

class A:

def showItself(self):

print('A')

class B:

def showItself(self):

print('B')

class AB(A,B):

pass

class BA(B,A):

pass

如果父类函数名相同 优先调用左边的

ab = AB()

ba = BA()

ab.showItself()

ba.showItself()

A

B

调用被覆盖了的其他方法

方法1:

class AB2(A,B):

def showItself_B(self):

B.showItself(self)

ab2 =AB2()

ab2.showItself()

ab2.showItself_B()

A

B

方法2:

class AB3(A,B):

def showItself_B(self):

super(A,self).showItself()

ab3 = AB3()

ab3.showItself_B()

B

这个有点令人迷惑,为什么super(A,self).showItself()调用的却不是A的方法,而且A的父类是object,更没有这个方法

实际上这个是按照顺序来选择的,默认的super()调用的是第一个A,然后下一个是B

再python2中这个搜索顺序是深度优先搜索,而在python3中这个顺序是广度优先搜索

class A1(A):

def showItself(self):

print('A1')

class A2(A):

def showItself(self):

print('A2')

class A12(A1,A2):

def showItself(self):

super().showItself()

super(A1,self).showItself()

super(A2,self).showItself()

a12 = A12()

a12.showItself()

A1

A2

A

特殊方法

__str__和__repr__

用于当使用print的时候就会调用__str__方法去获取字符串

用于当使用交互模式直接输出变量的时候就会调用__repr__方法去获取字符串

class Astr1:

def __repr__(self):

return "这是__repr__方法的调用"

class Astr2:

def __str__(self):

return "这是__str__方法的调用"

print(Astr1())

print(Astr2())

这是__repr__方法的调用

这是__str__方法的调用

Astr1()

这是__repr__方法的调用

Astr2()

__iter__和__next__

当对象需要使用for循环的时候,必须要去实现__iter__方法,返回一个迭代对象

然后迭代对象的__next__方法会被调用

class A_iter:

a = 0

def __iter__(self):

return self

def __next__(self):

A_iter.a+=1

if A_iter.a>10:

raise StopIteration()##终止循环

return A_iter.a

a_iter = A_iter()

for i in a_iter:

print(i,end=" ")

1 2 3 4 5 6 7 8 9 10

__getitem__

__getitem__是用于取序列元素的

一般要分为数字和切片,分别处理

class A_getitem:

def __getitem__(self,n):

if isinstance(n,int):#索引为数字

return n

if isinstance(n,slice):#索引为切片

return [x for x in range(n.start,n.stop)]

a = A_getitem()

print(a[100])

print(a[10:20])

100

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

__getattr__

用于返回未定义的参数

__getattribute__与 __getattr__的区别

当每次调用属性时,python会无条件进入__getattribute__中,不论属性存在与否

而__getattr__只会在找不到属性的时候调用

class A_attr:

def __getattribute__(self,attr):

return attr

a = A_attr()

print(a.name)

name

__call__

将对象本身视为一个方法,调用的就是__call__

class A_call:

def __call__(self):

print('__call__方法被调用')

a = A_call()

a()

__call__方法被调用

判断对象是否能被作为函数调用使用callable()函数

print(callable("123"))

print(callable(a))

False

True

枚举类型

#导入枚举的包

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

Month.Jan

本文地址:https://blog.csdn.net/qq754772661/article/details/107065325

希望与广大网友互动??

点此进行留言吧!

python函数名词解释_python的面向对象程序设计(名词解释及实例)相关推荐

  1. python函数参数列表_python函数列表

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! python函数函数是python里组织代码的最小单元,python函数包含以下 ...

  2. python类与对象作业_荐富贵和你一起复习Python(第10篇)— 面向对象程序设计

    继续复习Python,今日复习 -- 面向对象程序设计,中间会有自己的心得体会,要是有什么错误或者补充可直接评论或者私信哟. 面向对象程序设计 面向对象程序设计的思想主要针对大型软件设计提出,能够很好 ...

  3. python函数的命名_python函数命名

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 命名空间的生命周期名称空间的生命周期 内置名称空间:(最长)只要 python解 ...

  4. python函数画圆_python圆形_python圆形绘制_python圆形函数 - 云+社区 - 腾讯云

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 今天上课老师布置了一道pthon的课题,关键是和数学有关数学又是我的弱项头有点小 ...

  5. python函数五要素_Python安装及关键要素

    一.Python定义 shell编程: 控制语言:胶水语言 框架:web应用开发 二.Python性能优化工具 Psyco: python语言是一个扩展模块,可以即时对程序代码进行专业的算法优化,可以 ...

  6. python函数五要素_python之基础篇(二)

    防伪码:忘情公子著 一.面向过程与面向对象 面向过程: 以指令为中心,由指令去处理数据 只要考虑如何组织代码去解决问题 面向对象: 以数据为中心,所有的处理代码都围绕数据展开 要考虑如何设计数据结构组 ...

  7. python函数内计时_Python函数执行计时

    Python函数计时 使用threading的timer定时器 from threading import timer import time def time_limit(interval): de ...

  8. python 函数参数注释_Python中函数添加注释 如何正确的为函数添加注释说明

    在前面鳄鱼君对Python的注释只是简单的提示一下,没有详细说明,在这片文章中会对Python中的一些注释方法进行说明,它非常重要. 在Python中单行注释和多行注释非常的简单: Python中文编 ...

  9. python函数手册 下载_python函数手册

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 这个时候,为了避免反复编写相同的代码,我们可以使用一个函数来对某段代码块进行封装 ...

最新文章

  1. 正确导入svn拉取的工程
  2. 深夜,学妹说她想做Python数据分析师
  3. LeetCode MySQL 1321. 餐馆营业额变化增长(over窗口函数)
  4. vue项目引入CNZZ数据专家(方法汇总篇)
  5. COCI 2018/2019 CONTEST #2 Solution
  6. less与SASS学习心得
  7. Google Cloud Platform中没有Active Directory域的可用性组
  8. 麦肯锡用 160 页报告告诉我们:13 年后 8 亿人的饭碗会被机器人抢了
  9. 测试VGA12H直接写屏速度 V1.1
  10. Atitit 工作流之道 艾提拉著 BPM,即业务流程管理 目录 1. 流程入门 思想 历史 分类 1 第二篇 第2章 初识工作流 2 1.1. 2.3 工作流技术相关规范  2.3.1 W
  11. Mybatis-代码走查问题整理
  12. android translateanimation动画,Android 动画之TranslateAnimation应用详解
  13. c语言中 输出操作是由库函数,【判断题】在 C语言中,输入操作是由库函数scanf完成,输出操作是由库函数printf完成 。...
  14. python富翁与穷人_穷人和富人就差1%的运气——python模拟社会财富分配游戏
  15. antd vue实现日历功能——添加放假时间功能——基础积累
  16. EV录屏怎么把自己的摄像头放进去,摄像头好的,但是人像很花,看不清人脸
  17. JS 小坑 - AJAX请求的小坑,请求接口404
  18. Kinect动作捕捉的改进
  19. Web应用对接支付宝当面付解决方案
  20. 16进制几个字符是一个字节

热门文章

  1. error:type/value mismatch at ... ::iterator
  2. 运维与微服务结合?深度解析微服务框架Tars整体解决方案
  3. 关于计算机的知识作文,有关电脑的作文
  4. 拼多多2018年校招真题
  5. Win10 添加打印机最后一步提示没有权限
  6. 苹果M1芯片MacBook/iMac/Mac mini降级或者重装系统教程
  7. 汇编(二)——ARM数据处理指令——算术运算、数据传送
  8. prometheus服务配置Altermanager监控告警
  9. 公众号怎么设置滑动文字_这种微信公众号里面滑动是怎么操作的?
  10. 狼人杀c语言代码,1089 狼人杀-简单版——C/C++实现