一、类

1.1,构造函数,析构函数

#!/bin/python

classdog():def __init__(self, age, name):

self.age=age

self.name=namedefprint_self(self):print('Dog name is %s' %(self.name))print('Dog age is %d' %(self.age))

a= dog(10, 'alaski')

a.print_self()

输出结果:

Dog name isalaski

Dog ageis 10

析构函数

#!/bin/python

classdog():def __init__(self, age, name):

self.age=age

self.name=namedefprint_self(self):print('Dog name is %s' %(self.name))print('Dog age is %d' %(self.age))def __del__(self):print("delete dog object %s" %(self.name))

a= dog(10, 'alaski')

a.print_self()

输出结果:

Dog name isalaski

Dog ageis 10delete 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官方开发人员使用;

公有,私有变量

#!/bin/python

classdog():def __init__(self, age, name):

self.age=age

self.name=name

self.__type = 'dog'

defprint_self(self):print('Dog name is %s' %(self.name))print('Dog age is %d' %(self.age))print('Animal type is %s' %(self.__type))

a= dog(10, 'alaski')

a.print_self()print(a.name)#AttributeError: 'dog' object has no attribute '__type'

print(a.__type)

输出结果:

Dog name isalaski

Dog ageis 10Animal typeisdog

alask

1.3,函数

公有函数,私有函数

#!/bin/python

classdog():def __init__(self, age, name):

self.age=age

self.name=name

self.__type = 'dog'

defprint_self(self):print('Dog name is %s' %(self.name))print('Dog age is %d' %(self.age))print('Animal type is %s' %(self.__type))defsmile(self):print('Dog(%s) is smiling' %(self.name))

self.__set_smiling()def __set_smiling(self):

self.__attitude = 'smile'a= dog(10, 'alaski')

a.smile()#AttributeError: 'dog' object has no attribute '__set_smiling'

a.__set_smiling()

输出结果:

Dog(alaski) is smiling

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

1.4,static变量和函数

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

二,继承

2.1,继承

#!/bin/pythonclassperson:

def __init__(self):

print("person is intialized")

def say(self):

print("person is saying")classdriver(person):

def __init__(self):

super().__init__()

print("i am a driver")

def say(self):

print("driver is saying")

a=driver()

a.say()

输出结果:

person isintialized

i am a driver

driveris saying

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

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

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

代码:

#!/bin/python

classperson:def __init__(self):print("person is intialized")defsay(self):print("person is saying")def __say_to_self(self):print('i am saying sth to myself')classdriver(person):def __init__(self):

super().__init__()

super().__say_to_self()print("i am a driver")defsay(self):print("driver is saying")

a=driver()

a.say()

报错:

person isintialized

Traceback (most recent call last):

File"class2.py", line 20, in a=driver()

File"class2.py", line 14, in __init__super().__say_to_self()

AttributeError:'super' object has no attribute '_driver__say_to_self'

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

#!/bin/python

classperson:def __init__(self):print("person is intialized")defsay(self):print("person is saying")def __say_to_self(self):print('i am saying sth to myself')def_say_to_other(self):print('i am saying sth to other, and the saying is listened by all of them')classdriver(person):def __init__(self):

super().__init__()

super()._say_to_other()print("i am a driver")defsay(self):print("driver is saying")

a=driver()

a._say_to_other()

输出:

person isintialized

i am saying sth to other,and the saying islistened by all of them

i am a driver

i am saying sth to other,and the saying is listened by all of them

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

三、导入类

3.1,导入单个类

文件: car.py#!/bin/python

classCar:

year=0

brand= ''series= ''

def __init__(self, brand, series, year):

self.brand=brand

self.series=series

self.year=yeardefget_car_desc(self):

desc= ''desc+= ("car info: [year:%d] [brand:%s] [series:%s]" %(self.year, self.brand, self.series))returndesc

文件: my_car.py#!/bin/python

from car importCar

c= Car('tesla', 'Model X', 2016)

d=c.get_car_desc()print(d)

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

from [A] import [B]

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

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

文件:car.py#!/bin/python

classCar:

year=0

brand= ''series= ''

def __init__(self, brand, series, year):

self.brand=brand

self.series=series

self.year=yeardefget_car_desc(self):

desc= ''desc+= ("car info: [year:%d] [brand:%s] [series:%s]" %(self.year, self.brand, self.series))returndescclassElectricCar(Car):def __init__(self, brand, series, year):

super().__init__(brand, series, year)defget_range():return "100 miles"文件:my_car.py#!/bin/python

from car importCarfrom car importElectricCar

c= Car('bmw', 'X3', 2016)

d=c.get_car_desc()print(d)

tesla= ElectricCar('tesla', 'Model S', 2017)

d=tesla.get_car_desc()print(d)

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

和3.2公用一个例子

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

3.4,导入整个模块

#!/bin/python

importcar

c= car.Car('Nissan', 'Sylphy', 2012)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

python class函数报错_24 【python入门指南】class相关推荐

  1. python read函数报错_python 使用read_csv读取 CSV 文件时报错

    读取csv文件时报错 df = pd.read_csv('c:/Users/NUC/Desktop/成绩.csv' ) Traceback (most recent call last): File ...

  2. python def函数报错详解_python自定义函数def的应用详解

    这篇文章主要介绍了python自定义函数def的应用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 这里是三岁,来和大家唠唠 ...

  3. python def函数报错详解_JSer 快速入门 Python 之函数详解

    前一篇文章,用一天的时间,通过与 JavaScript 做对比的方式,快速领略了 Python 全貌. 梳理了那么多,若忽略细节差异,两门语言只有两个重要差异: 1.书写风格上大相同 2.功能覆盖上, ...

  4. python时间函数报错_python3中datetime库,time库以及pandas中的时间函数区别与详解...

    1介绍datetime库之前 我们先比较下time库和datetime库的区别 先说下time 在 Python 文档里,time是归类在Generic Operating System Servic ...

  5. python def函数报错详解_【python】详解python函数定义 def()与参数args、可变参数*args、关键参数**args使用实例...

    Python内置了很多函数,可以直接调用.Python内置的函数可以通过官方文档查看.也可以通过help()查看帮助信息.函数名是指向函数对象的引用,把函数名赋给变量,相当于给函数起了别名. 1. 定 ...

  6. python class函数报错_Python 的函数是第一类 First-Class 对象

    Python的函数是第一类对象(first-class object).你可以把一个函数复制给变量,或者把函数存储在一个结构中.可以像参数一样把函数传递进另一个函数,还可以从一个函数中返回另一个函数. ...

  7. python def函数报错详解_python所有内置函数的定义详解

    >>> def hello_world(): ...     print('Hello,world!')   # 注意函数体要有缩进 ... >>> hello_w ...

  8. python def函数报错详解_Python函数详解

    一.Python中函数的概念 1.python中函数概念 Python中函数是逻辑结构化和过程化的一种编程方法. 2.python中函数定义方法解释 def name(a): "The fu ...

  9. python class函数报错_Python multiprocess pool模块报错pickling error问题解决方法分析

    本文实例讲述了Python multiprocess pool模块报错pickling error问题解决方法.分享给大家供大家参考,具体如下: 问题 之前在调用class内的函数用multiproc ...

最新文章

  1. 控制行输入以下两句命令16倍速播放青年大学习
  2. linux后台执行命令:amp;与nohup的用法
  3. 数据结构(莫队算法):国家集训队2010 小Z的袜子
  4. “最粉嫩”的JVM垃圾回收器及算法,王者笔记!
  5. 演示如何使用application.yml文件
  6. 强大的.NET反编译工具Reflector及插件(转载)
  7. 计算机文化基础知识点文件,计算机文化基础知识点.doc
  8. Java怎么重复使用套接字_在java中连续地通过套接字传输数据
  9. bert 无标记文本 调优_使用BERT准确标记主观问答内容
  10. wamp php启动不成功,wamp的mysql 启动失败解决
  11. css3 如何动态画一条直线_素描基础学习课:素描长直线的画法!把直线画直的关键!...
  12. vue js中解决二进制转图片显示问题
  13. 微信快速开发框架(五)-- 利用快速开发框架,快速搭建微信浏览博客园首页文章...
  14. 机器学习算法基础8-Nagel-Schreckenberg交通流模型-公路堵车概率模型
  15. python实现递归和非递归求两个数最大公约数、最小公倍数
  16. text-overflow:ellipsis
  17. 英语系大一计算机课程有哪些,英语专业大一学习计划.docx
  18. adb 切换默认桌面,OPPO默认桌面替换教程
  19. 卖肉了也没火的十大悲催女星
  20. Java代码分层规范

热门文章

  1. Python中字符串截取
  2. 如何读取PLC的寄存器地址和点表?
  3. 电子学会图形化二级编程题解析含答案:魔法星空
  4. IDEA报错:Plugin ‘org.springframework.boot:spring-boot-maven-plugin:‘ not found
  5. 共享电单车属于哪个部门管理_对小区物业服务不满找谁投诉?哪个部门负责管理...
  6. 用python找出400多万次KDJ金叉死叉,胜率有多高?附代码
  7. java vbs_一键定位配置JAVA SDK 环境变量 VBS脚本全自动操作正式开源
  8. Bootstrap入门使用
  9. 【tkinter组件专栏】LabelFrame:规划布局frame的小老弟
  10. 一点关于优化手写笔迹