python基础---->python的使用(六)

时间:2022-08-31 08:10:56

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

python中的类知识

一、class的属性引用与实例

class MyClass():
'''A simple exampel class'''
i = 12345 # class variable shared by all instances def __init__(self, realpart, imagpart):
self.real = realpart # instance variable unique to each instance
self.imag = imagpart def f(self):
return self.real + 'hello' x = MyClass('huhx', 'linux')
print(x.real, x.imag, x.i, MyClass.i) # MyClass.real会报错
print(MyClass.__doc__, x.__doc__) # A simple exampel class
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的实例这两个属性值可能是不一样的。关于这个,请看下面的这个例子
 class Dog():
tricks = [] # def __init__(self):
# self.tricks = [] def add_tricks(self, trick):
self.tricks.append(trick)
d = Dog()
d.add_tricks('roll over')
e = Dog()
e.add_tricks('play dead')
print(d.tricks, e.tricks) # ['roll over', 'play dead'] ['roll over', 'play dead']

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

def f1(self, x, y):
return min(x, y) class C():
f = f1
def g(self):
return 'hello world' h = g classC = C()
print(C.f(classC, 2, 45), classC.f(2, 45)) # 2 2
print(classC.h()) # hello world
classC.h = 'hello abc'
print(classC.g(), classC.h) # hello world hello abc

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

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

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

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>

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

class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
self._name = name def print_score(self):
print('%s: %s' % (self.__name, self.__score)) bart = Student('Bart Simpson', 59)
# print(bart.__name) # AttributeError: 'Student' object has no attribute '_name'
print(bart._Student__name)
print(bart._name) # 约定是外部不能访问,但是实际上外部可以访问。
print(type(bart)) # <class '__main__.Student'>
print(isinstance(bart, Student), issubclass(Student, object)) # True True

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

class Employee:
pass john = Employee() # Create an empty employee record # Fill the fields of the record
Employee.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
print(john.name) # John Doe

三、python类中的Generators与Iterators

# one way
for ele in [1, 2, 3]:
print(ele, end=' ')
print() # iter
s = 'abc'
it = iter(s)
print(next(it), next(it), next(it), end=' ')
print() # Generators
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index] for char in reverse('huhx'):
print(char, end=' ')
print() # class next and iter
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data) def __iter__(self):
return self def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index] rev = Reverse('linux')
for char in rev:
print(char, end=' ') # 1 2 3
# a b c
# x h u h
# x u n i l

四、python类的一些特殊方法

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

class Student(object):
__slots__ = ('name', 'age') s = Student()
s.name = 'huhx'
s.age = 45
s.score = 45

运行会报错:

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

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

class Student(object):
@property
def score(self):
return 'score = ' + str(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 def __str__(self):
return 'student info: ' + self.score def __getattr__(self, item):
if item == 'address':
return 'china'
elif item == 'attr_fun':
return lambda x: x * x s = Student()
s.score = 60
print(s.score) # score = 60
print(s.address) # china
print(s.attr_fun(4)) #
print(s) # student info: score = 60
s.score = 999 # 抛出异常

友情链接

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

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

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

  2. python基础----&gt&semi;python的使用&lpar;三&rpar;

    今天是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. css3 自定义字体的使用方法

    @font-face是CSS3中的一个模块,他主要是把自己定义的Web字体嵌入到你的网页中,随着@font-face模块的出现,我们在Web的开发中使用字体不怕只能使用Web安全字体,你们当中或许有许 ...

  2. C&num; 在Word文档中生成条形码

    C# 在Word文档中生成条形码 简介 条形码是由多个不同的空白和黑条按照一定的顺序组成,用于表示各种信息如产品名称.制造商.类别.价格等.目前,条形码在我们的日常生活中有着很广泛的应用,不管是在图书 ...

  3. Readonly和Disabled的区别

    readonly 把输入的字段设为只读,但是没有禁用 readonly=” readonly”; disabled 禁用一个input元素. disabled="disabled" ...

  4. SuperMapDeskTop中去除面图层边框

    0.项目中有个功能需要在超图DeskTop中修改面图层的符号,将要素的边框去掉.搞来搞去这个功能并不像ArcGisDeskTop一样直接有无边框的符号,通过请教,通过修改面图层的线样式的RGB颜色管理 ...

  5. -&lowbar;-&num;【事件】keyCode

  6. HTML文档类型

    在HMTL5中页面的最顶端代码就是: <!DOCTYPE html> 为何要如此定义.书写呢? 首先引入一个概念:文档类型,英译为:Document type,缩写成:doctype. 文 ...

  7. tensorflow变量-【老鱼学tensorflow】

    在程序中定义变量很简单,只要定义一个变量名就可以,但是tensorflow有点类似在另外一个世界,因此需要通过当前的世界中跟tensorlfow的世界中进行通讯,来告诉tensorflow的世界中定义 ...

  8. c——动态数组

    动态数组的实现 #include<stdio.h> #include<stdlib.h> int main(){ int i,n,*a; scanf("%d&quot ...

  9. javascript基础学习系列-1

    JavaScript简介 JavaScript的用途 JavaScript用来制作web页面交互效果,提升用户体验. web前端三层来说:w3c的规范:行内样式(淘汰) 结构层 HTML 从语义的角度 ...

  10. chrome 总崩溃的正确解决方法

    解决办法: 原因就是 C:\Windows\System32\drivers\bd0001.sys 这个文件 可以把这个文件删除,或者重命名,删除或者重命名后一定要重启电脑,再打开Chrome就OK了 ...