一、类

1.1,构造函数,析构函数

  1. #!/bin/python
  2.  
  3. class dog():
  4. def __init__(self, age, name):
  5. self.age = age
  6. self.name = name
  7. def print_self(self):
  8. print('Dog name is %s' %(self.name))
  9. print('Dog age is %d' %(self.age))
  10.  
  11. a = dog(10, 'alaski')
  12. a.print_self()

输出结果:

  1. Dog name is alaski
  2. Dog age is 10

析构函数

  1. #!/bin/python
  2.  
  3. class dog():
  4. def __init__(self, age, name):
  5. self.age = age
  6. self.name = name
  7. def print_self(self):
  8. print('Dog name is %s' %(self.name))
  9. print('Dog age is %d' %(self.age))
  10. def __del__(self):
  11. print("delete dog object %s" %(self.name))
  12.  
  13. a = dog(10, 'alaski')
  14. a.print_self()

输出结果:

  1. Dog name is alaski
  2. Dog age is 10
  3. delete dog object alaski

以上介绍了构造函数:__init__,析构函数:__del__。

1.2,变量

公有变量,私有变量

首先介绍一个背景,python对于类有个默认预定:

vvv:正常以a-z开头的变量,或者方法,python认定其为公有变量或者函数;

_vvv:(单前置下划线,私有化属性或方法,类对象和子类可以访问,from somemodule import *禁止导入)这个是从参考资料中查到的,我没有验证过【参考资料1】;

__vvv:如果以两个下划线开头,后面再接a-z的话,python认定其为私有变量或者函数;

__vv__:如果以两个下划线开头,并且两个下划线截止的格式,python认定其为保留格式,python用于内置函数或者扩展用法,应用程序杜绝这种写法,仅适用于python官方开发人员使用;

公有,私有变量

  1. #!/bin/python
  2.  
  3. class dog():
  4.  
  5. def __init__(self, age, name):
  6. self.age = age
  7. self.name = name
  8. self.__type = 'dog'
  9.  
  10. def print_self(self):
  11. print('Dog name is %s' %(self.name))
  12. print('Dog age is %d' %(self.age))
  13. print('Animal type is %s' %(self.__type))
  14.  
  15. a = dog(10, 'alaski')
  16. a.print_self()
  17. print(a.name)
  18. #AttributeError: 'dog' object has no attribute '__type'
  19. print(a.__type)

输出结果:

  1. Dog name is alaski
  2. Dog age is 10
  3. Animal type is dog
  4. alask

1.3,函数

公有函数,私有函数

  1. #!/bin/python
  2.  
  3. class dog():
  4.  
  5. def __init__(self, age, name):
  6. self.age = age
  7. self.name = name
  8. self.__type = 'dog'
  9.  
  10. def print_self(self):
  11. print('Dog name is %s' %(self.name))
  12. print('Dog age is %d' %(self.age))
  13. print('Animal type is %s' %(self.__type))
  14.  
  15. def smile(self):
  16. print('Dog(%s) is smiling' %(self.name))
  17. self.__set_smiling()
  18.  
  19. def __set_smiling(self):
  20. self.__attitude = 'smile'
  21.  
  22. a = dog(10, 'alaski')
  23. a.smile()
  24.  
  25. #AttributeError: 'dog' object has no attribute '__set_smiling'
  26. a.__set_smiling()

输出结果:

  1. Dog(alaski) is smiling

可以看到,dog类中的私有函数为__set_smiling,它可以被类中的函数调用,但是无法在类外使用(使用会报错)。

1.4,static变量和函数

目前我查到的资料中显示,python并不天然支持static变量和static函数。

二,继承

2.1,继承

  1. #!/bin/python
  2.  
  3. class person:
  4. def __init__(self):
  5. print("person is intialized")
  6. def say(self):
  7. print("person is saying")
  8.  
  9. class driver(person):
  10. def __init__(self):
  11. super().__init__()
  12. print("i am a driver")
  13. def say(self):
  14. print("driver is saying")
  15.  
  16. a = driver()
  17. a.say()

输出结果:

  1. person is intialized
  2. i am a driver
  3. driver is saying

driver继承了person类,并在初始化的时候调用了父类的初始化构造函数。

2.2,父类的私有类是否能被继承?

如果父类的函数是私有函数,也就是以__开头的,是不允许子类访问的。

代码:

  1. #!/bin/python
  2.  
  3. class person:
  4. def __init__(self):
  5. print("person is intialized")
  6. def say(self):
  7. print("person is saying")
  8. def __say_to_self(self):
  9. print('i am saying sth to myself')
  10.  
  11. class driver(person):
  12. def __init__(self):
  13. super().__init__()
  14. super().__say_to_self()
  15. print("i am a driver")
  16.  
  17. def say(self):
  18. print("driver is saying")
  19.  
  20. a = driver()
  21. a.say()

报错:

  1. person is intialized
  2. Traceback (most recent call last):
  3. File "class2.py", line 20, in <module>
  4. a = driver()
  5. File "class2.py", line 14, in __init__
  6. super().__say_to_self()
  7. AttributeError: 'super' object has no attribute '_driver__say_to_self'

2.3,设定某些函数可以被自身及其子类所访问

  1. #!/bin/python
  2.  
  3. class person:
  4. def __init__(self):
  5. print("person is intialized")
  6. def say(self):
  7. print("person is saying")
  8. def __say_to_self(self):
  9. print('i am saying sth to myself')
  10. def _say_to_other(self):
  11. print('i am saying sth to other, and the saying is listened by all of them')
  12.  
  13. class driver(person):
  14. def __init__(self):
  15. super().__init__()
  16. super()._say_to_other()
  17. print("i am a driver")
  18.  
  19. def say(self):
  20. print("driver is saying")
  21.  
  22. a = driver()
  23. a._say_to_other()

输出:

  1. person is intialized
  2. i am saying sth to other, and the saying is listened by all of them
  3. i am a driver
  4. i am saying sth to other, and the saying is listened by all of them

设定的_say_to_other是可以被子类所访问的,但是它和c++中的protected不一样。以单个下划线开头的函数,和公开方法是一样的,既可以被自身和子类访问,又能在类外所访问。

三、导入类

3.1,导入单个类

  1. 文件: car.py
  2. #!/bin/python
  3.  
  4. class Car:
  5. year = 0
  6. brand = ''
  7. series = ''
  8.  
  9. def __init__(self, brand, series, year):
  10. self.brand = brand
  11. self.series = series
  12. self.year = year
  13.  
  14. def get_car_desc(self):
  15. desc = ''
  16. desc += ("car info: [year:%d] [brand:%s] [series:%s]" % (self.year, self.brand, self.series))
  17. return desc
  18.  
  19. 文件: my_car.py
  20. #!/bin/python
  21. from car import Car
  22.  
  23. c = Car('tesla', 'Model X', 2016)
  24. d = c.get_car_desc()
  25. print(d)

可以在my_car.py中引入类Car,引用时候使用from car import Car

from [A] import [B]

A要和文件名前缀保持一致,B要和类名保持一致,并且要区分大小写。

3.2,在一个模块中存储多个类

  1. 文件:car.py
  2. #!/bin/python
  3.  
  4. class Car:
  5. year = 0
  6. brand = ''
  7. series = ''
  8.  
  9. def __init__(self, brand, series, year):
  10. self.brand = brand
  11. self.series = series
  12. self.year = year
  13.  
  14. def get_car_desc(self):
  15. desc = ''
  16. desc += ("car info: [year:%d] [brand:%s] [series:%s]" % (self.year, self.brand, self.series))
  17. return desc
  18.  
  19. class ElectricCar(Car):
  20. def __init__(self, brand, series, year):
  21. super().__init__(brand, series, year)
  22.  
  23. def get_range():
  24. return "100 miles"
  25.  
  26. 文件:my_car.py
  27. #!/bin/python
  28. from car import Car
  29. from car import ElectricCar
  30.  
  31. c = Car('bmw', 'X3', 2016)
  32. d = c.get_car_desc()
  33. print(d)
  34.  
  35. tesla = ElectricCar('tesla', 'Model S', 2017)
  36. d = tesla.get_car_desc()
  37. print(d)

3.3,从一个模块中导入多个类

和3.2公用一个例子

from car import Car, ElectricCar可以存储和导入多个类

3.4,导入整个模块

  1. #!/bin/python
  2.  
  3. import car
  4.  
  5. c = car.Car('Nissan', 'Sylphy', 2012)
  6. print(c.get_car_desc())

car.py仍然使用之前的文件,但是my_car.py需要修改下。

导入整个模块使用import car,但是初始化实例时候需要使用全称,不能简化:a = car.Car()这种方式。

参考资料:

1,https://www.cnblogs.com/semon-code/p/8242062.html

24 【python入门指南】class的更多相关文章

  1. Python入门指南(超详细)

    Python 是一门非常容易上手的语言,通过查阅资料和教程,也许一晚上就能写出一个简单的爬虫.但 Python 也是一门很难精通的语言,因为简洁的语法背后隐藏了许多黑科技.本文主要针对的读者是: 毫无 ...

  2. Python 入门指南

    Release: 3.4 Date: March 29, 2014 Python 是一门简单易学且功能强大的编程语言. 它拥有高效的高级数据结构,并且能够用简单而又高效的方式进行面向对象编程. Pyt ...

  3. 25 【python入门指南】如何编写测试代码

    python如何编写测试代码 python内置了unittest,使得写应用层的单元测试变得超乎寻常的简单. 1,执行单个测试函数 #!/bin/python import unittest clas ...

  4. python入门教程链接

    python安装 选择 2.7及以上版本 linux: 一般都自带 windows: https://www.python.org/downloads/windows/ mac os: https:/ ...

  5. Python入门一:简单得不能再简单了##

    从python的语法上看,简单得不能再简单了. 想学它,请移步廖雪峰python2.7教程以及python3.这实在是最好的入门教程.参考资料太多: 外国的教程 Python 入门指南 Python ...

  6. Python不完全入门指南

    适用范围: 有一定编程基础,想快速入门python的人群 说明: 使用jupyter notebook编写,可以使用nbviewer网站进行查看. Python不完全入门指南 项目放在github上, ...

  7. Python 30分钟入门指南

    Python 30分钟入门指南 为什么 OIer 要学 Python? Python 语言特性简洁明了,使用 Python 写测试数据生成器和对拍器,比编写 C++ 事半功倍. Python 学习成本 ...

  8. Python 30分钟快速入门指南

    学习地址 中文版:Python 30分钟入门指南 英文版:Learn X in Y minutes 学习时间 2019/03/10 19:00 - 19:32,多用了2分钟.

  9. Python 极速入门指南

    前言 转载于本人博客. 面向有编程经验者的极速入门指南. 大部分内容简化于 W3School,翻译不一定准确,因此标注了英文. 包括代码一共两万字符左右,预计阅读时间一小时. 目前我的博客长文显示效果 ...

随机推荐

  1. mobile-net v2 学习记录。我是菜鸡!

    声明:只是自己写博客总结下,不保证正确性,我的理解很可能是错的.. 首先,mobile net V1的主要特点是: 1.深度可分离卷积.用depth-wise convolution来分层过滤特征,再 ...

  2. C++复习:继承与派生

    1继承概念 面向对象程序设计有4个主要特点:抽象.封装.继承和多态性.说了类和对象,了解了面向对象程序设计的两个重要特征一数据抽象与封装,已经能够设计出基于对象的程序,这是面向对象程序设计的基础. 要 ...

  3. Unable to locate Spring NamespaceHandler for XML schema namespace

    1. 问题 本文将讨论Spring中最常见的配置问题 —— Spring的一个命名空间的名称空间处理程序没有找到. 大多数情况下,是由于一个特定的Spring的jar没有配置在classpath下,让 ...

  4. [CI]CodeIgniter视图 & 模型 & 控制器

    ---------------------------------------------------------------------------------------------------- ...

  5. Matlab实现BP网络识别字母

    训练样本空间   每个样本使用5×5的二值矩阵表征一个字母.一共10个字母类型,分别是N,I,L,H,T,C,E,F,Z,V.每个字母9个样本.共90个. N1=[1,0,0,0,1; 1,0,0,0 ...

  6. 使用__slots__限制实例的属性

    1.给实例化的对象添加新的属性 看下面一段代码,然后给实例化的对象s添加或者修改属性 class Student(object): name='china' s = Student() s1=Stud ...

  7. opencv批量读取图片

    #include<opencv2/opencv.hpp>using namespace cv;using namespace std;int main(){    int num=4;// ...

  8. php urldecode 与rawdecode

    php urldecode 解码给出的已编码字符串中的任何 %##. 加号('+')被解码成一个空格字符 php rawurldecode 返回字符串,此字符串中百分号(%)后跟两位十六进制数的序列都 ...

  9. Manifest File

    [Manifest File] on every build, webpack generates some webpack runtime code, which helps webpack do ...

  10. node 加载逻辑

    [node 加载逻辑] require(X) from module at path Y . If X is a core module, a. return the core module b. S ...