这里记录一下python中关于class类的一些知识。不解释就弄不懂的事,就意味着怎样解释也弄不懂。

python中的类知识

一、class的属性引用与实例

  1. class MyClass():
  2. '''A simple exampel class'''
  3. i = 12345 # class variable shared by all instances
  4.  
  5. def __init__(self, realpart, imagpart):
  6. self.real = realpart # instance variable unique to each instance
  7. self.imag = imagpart
  8.  
  9. def f(self):
  10. return self.real + 'hello'
  11.  
  12. x = MyClass('huhx', 'linux')
  13. print(x.real, x.imag, x.i, MyClass.i) # MyClass.real会报错
  14. print(MyClass.__doc__, x.__doc__) # A simple exampel class
  15. print(MyClass.f(x), x.f()) # huhxhello huhxhello
  • When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.所以python类的__init__()方法类似于java中构造方法。
  • MyClass类的属性i在所有MyClass的实例中共享,而real和imag就是实例私有,每个MyClass的实例这两个属性值可能是不一样的。关于这个,请看下面的这个例子
  1. class Dog():
  2. tricks = []
  3.  
  4. # def __init__(self):
  5. # self.tricks = []
  6.  
  7. def add_tricks(self, trick):
  8. self.tricks.append(trick)
  9. d = Dog()
  10. d.add_tricks('roll over')
  11. e = Dog()
  12. e.add_tricks('play dead')
  13. print(d.tricks, e.tricks) # ['roll over', 'play dead'] ['roll over', 'play dead']

如果注释掉第二行,打开4、5行。运行的结果:['roll over'] ['play dead']。类的方法还可以定义在类的外面,测试用例如下:

  1. def f1(self, x, y):
  2. return min(x, y)
  3.  
  4. class C():
  5. f = f1
  6. def g(self):
  7. return 'hello world'
  8.  
  9. h = g
  10.  
  11. classC = C()
  12. print(C.f(classC, 2, 45), classC.f(2, 45)) # 2 2
  13. print(classC.h()) # hello world
  14. classC.h = 'hello abc'
  15. print(classC.g(), classC.h) # hello world hello abc

上述的例子可以看到f1定义在类C的外面,可以正常使用。而且在类中赋值h = g,修改h的值。不会影响到g,说明类中的方法赋值是值传递。

二、python类的继承与访问权限

python的继承语法如下,可以支持多层继承。

  1. class DerivedClassName(Base1, Base2, Base3):
  2. <statement-1>
  3. .
  4. .
  5. .
  6. <statement-N>

关于python的私有变量,提供下述的代码:

  1. class Student(object):
  2. def __init__(self, name, score):
  3. self.__name = name
  4. self.__score = score
  5. self._name = name
  6.  
  7. def print_score(self):
  8. print('%s: %s' % (self.__name, self.__score))
  9.  
  10. bart = Student('Bart Simpson', 59)
  11. # print(bart.__name) # AttributeError: 'Student' object has no attribute '_name'
  12. print(bart._Student__name)
  13. print(bart._name) # 约定是外部不能访问,但是实际上外部可以访问。
  14. print(type(bart)) # <class '__main__.Student'>
  15. print(isinstance(bart, Student), issubclass(Student, object)) # True True

python中可以定义一个空的类,属性和方法可以自行添加。

  1. class Employee:
  2. pass
  3.  
  4. john = Employee() # Create an empty employee record
  5.  
  6. # Fill the fields of the record
  7. Employee.name = 'John Doe'
  8. john.dept = 'computer lab'
  9. john.salary = 1000
  10. print(john.name) # John Doe

三、python类中的Generators与Iterators

  1. # one way
  2. for ele in [1, 2, 3]:
  3. print(ele, end=' ')
  4. print()
  5.  
  6. # iter
  7. s = 'abc'
  8. it = iter(s)
  9. print(next(it), next(it), next(it), end=' ')
  10. print()
  11.  
  12. # Generators
  13. def reverse(data):
  14. for index in range(len(data)-1, -1, -1):
  15. yield data[index]
  16.  
  17. for char in reverse('huhx'):
  18. print(char, end=' ')
  19. print()
  20.  
  21. # class next and iter
  22. class Reverse:
  23. """Iterator for looping over a sequence backwards."""
  24. def __init__(self, data):
  25. self.data = data
  26. self.index = len(data)
  27.  
  28. def __iter__(self):
  29. return self
  30.  
  31. def __next__(self):
  32. if self.index == 0:
  33. raise StopIteration
  34. self.index = self.index - 1
  35. return self.data[self.index]
  36.  
  37. rev = Reverse('linux')
  38. for char in rev:
  39. print(char, end=' ')
  40.  
  41. # 1 2 3
  42. # a b c
  43. # x h u h
  44. # x u n i l

四、python类的一些特殊方法

  Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:

  1. class Student(object):
  2. __slots__ = ('name', 'age')
  3.  
  4. s = Student()
  5. s.name = 'huhx'
  6. s.age = 45
  7. s.score = 45

运行会报错:

  1. Traceback (most recent call last):
  2. File "G:/Java/Go/program/2017-05-18/LearnPython1/test10/huhx5.py", line 8, in <module>
  3. s.score = 45
  4. AttributeError: 'Student' object has no attribute 'score'

  Python内置的@property装饰器就是负责把一个方法变成属性调用的。当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性。__str__()方法类似于java类中的toString方法。如下案例

  1. class Student(object):
  2. @property
  3. def score(self):
  4. return 'score = ' + str(self._score)
  5.  
  6. @score.setter
  7. def score(self, value):
  8. if not isinstance(value, int):
  9. raise ValueError('score must be an integer!')
  10. if value < 0 or value > 100:
  11. raise ValueError('score must between 0 ~ 100!')
  12. self._score = value
  13.  
  14. def __str__(self):
  15. return 'student info: ' + self.score
  16.  
  17. def __getattr__(self, item):
  18. if item == 'address':
  19. return 'china'
  20. elif item == 'attr_fun':
  21. return lambda x: x * x
  22.  
  23. s = Student()
  24. s.score = 60
  25. print(s.score) # score = 60
  26. print(s.address) # china
  27. print(s.attr_fun(4)) #
  28. print(s) # student info: score = 60
  29. s.score = 999 # 抛出异常

友情链接

python基础---->python的使用(六)的更多相关文章

  1. Python基础学习笔记(六)常用列表操作函数和方法

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-lists.html 3. http://www.liaoxuef ...

  2. python基础---->python的使用(三)

    今天是2017-05-03,这里记录一些python的基础使用方法.世上存在着不能流泪的悲哀,这种悲哀无法向人解释,即使解释人家也不会理解.它永远一成不变,如无风夜晚的雪花静静沉积在心底. Pytho ...

  3. Python基础--Python简介和入门

    ☞写在前面 在说Python之前,我想先说一下自己为什么要学Python,我本人之前也了解过Python,但没有深入学习.之前接触的语言都是Java,也写过一些Java自动化用例,对Java语言只能说 ...

  4. python基础-python解释器多版本共存-变量-常量

    一.编程语言的发展史 机器语言-->汇编语言-->高级语言,学习难度及执行效率由高到低,开发效率由低到高 机器语言:二进制编程,0101 汇编语言:用英文字符来代替0101编程 高级语言: ...

  5. python基础--python基本知识、七大数据类型等

    在此申明一下,博客参照了https://www.cnblogs.com/jin-xin/,自己做了部分的改动 (1)python应用领域 目前Python主要应用领域: 云计算: 云计算最火的语言, ...

  6. Python基础学习参考(六):列表和元组

    一.列表 列表是一个容器,里面可以放置一组数据,并且列表中的每个元素都具有位置索引.列表中的每个元素是可以改变的,对列表操作都会影响原来的列表.列表的定义通过"[ ]"来定义,元素 ...

  7. python基础学习笔记(六)

    学到这里已经很不耐烦了,前面的数据结构什么的看起来都挺好,但还是没法用它们做什么实际的事. 基本语句的更多用法 使用逗号输出 >>> print 'age:',25 age: 25 ...

  8. python基础整理笔记(六)

    一. 关于hashlib模块的一些注意点 hashlib模块用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512, MD ...

  9. 《Python基础教程》第六章:抽象(一)

    用def定义函数 __doc__是函数属性.属性名中的双下划线表示它是个特殊属性

随机推荐

  1. (转)最简单的基于FFmpeg的内存读写的例子:内存播放器

    ffmpeg内存播放解码 目录(?)[+] ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章 ...

  2. openssl创建自己的CA certificate

    Create a Certificate Authority private key (this is your most important key): $ openssl req -new -ne ...

  3. C# webbrowser判断页面是否加载完毕

    private void Form1_Load(object sender, EventArgs e) { webalipay.Url = new Uri("https://authzth. ...

  4. linux下nginx安裝

    1.yum安裝 yum安裝  http://nginx.org/packages/centos/7/noarch/RPMS/ 第一步: 安裝命令: yum localinstall http://ng ...

  5. 原理分析之一:从JDBC到Mybatis

    原理分析之一:从JDBC到Mybatis Mybatis学习(一)原生态的JDBC编程总结 -----系列 深入浅出MyBatis-快速入门

  6. app已损坏,打不开。你应该将它移到废纸篓。

    app已损坏,打不开.你应该将它移到废纸篓.(macOS Sierra 10.12) ,打开终端,执行 sudo spctl --master-disable 即可.

  7. 安卓开发笔记——Fragment+FragmentTabHost组件(实现新浪微博底部菜单)

    记得之前写过2篇关于底部菜单的实现,由于使用的是过时的TabHost类,虽然一样可以实现我们想要的效果,但作为学习,还是需要来了解下这个新引入类FragmentTabHost 之前2篇文章的链接: 安 ...

  8. SharePoint 2013 处理Promoted Links类型的List下的Tiles View的默认Webpart展示方式

    问题: 为了去掉Photo Gallery的水平滚动效果,更改为根据内容进行自适应宽度多行显示效果 Promoter link --> photo gallery Not horizontal ...

  9. Java学习之——JavaBeans

    1.什么是JavaBeans? JavaBeans是Java语言中可以重复使用的软件组件,它们是一种特殊的Java类,将很多的对象封装到了一个对象(bean)中.特点是 可序列化, 提供无参构造器, ...

  10. mysql对执行结果进行html格式的输出?输出html格式?

    需求描述: 在执行mysql命令的时候,有的时候需要将查询的结果输出到文件,如果想要html格式的,应该怎么输出, 在此记录下操作的过程. 1.通过tee命令结合--html输出查询结果到html文件 ...