零基础学Python注意事项(十)——类的使用
2019-08-01 23:10
239 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mango_ZZY/article/details/98114778
一、类的定义
[code]>>> class Dog(): def __init__(self,name,color): self.name=name self.color=color def A(self): print('这条狗叫'+self.name) def B(self): print('这条狗是'+self.color+'色的')
1.类=属性+方法
2.定义属性的时候,必须要用def __init__():,而且self是必不可少的,还要在其他形参前面
3.init 前后各是2个下划线
4.不一定非得是self,但是为了语法规范,统一都要用self
5.创建类的实例的时候,除了要把除了self以外的形参都赋值,如:
[code]>>> Dog1=Dog('ww','bbb')
6.实例调用方法:
[code]>>> Dog1.A() 这条狗叫ww >>> Dog1.B() 这条狗是bbb色的
7.如果想让函数或者属性变成私有的,则只需在函数名或者属性名前加2个下划线:__
[code]class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) >>> bart = Student('Bart Simpson', 98) >>> bart.__name Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute '__name'
8.若属性定义了初始值,则不用再提供形参:
[code]>>> class Dog(): def __init__(self,name,color): self.name=name self.color=color self.age=6
9.修改属性的值:可以直接在实例中修改,也可以通过定义类中的方法对其修改。
二、类的继承:
1.必须用super().__init__(),去继承父类的属性
[code]>>> class parent(): def __init__(self,name,age,tall): self.name=name self.age=age self.tall=tall >>> class child(parent): def __init__(self,name,age,tall): super().__init__(name,age,tall) >>> A=child('zzz',16,180) >>> A.name 'zzz' >>> A.age 16 >>> A.tall 180
2.重写父类的方法:若子类重写父亲的方法,即与父类的方法同名,则子类方法会覆盖父类方法
3.可以将某个类中的实例,作为另一个类中的属性
三、类的导入
1.form car import Car
2.from car import *
3.import car as C
相关文章推荐
- python3之IDLE使用注意事项
- 对象使用self注意事项 分类: python基础学习 2013-09-03 09:52 218人阅读 评论(0) 收藏
- boost.python 使用时注意小事项
- 1.2.4 在Python中使用向量化的技巧和注意事项
- python 使用注意事项
- Learning Python 014 使用 pip 工具的注意事项 --- 混淆的python2 和 python3
- Python中round函数使用注意事项
- python的subprocess的简单使用和注意事项
- Python3.x中beautifulsoup的使用注意事项
- python executemany的使用及注意事项
- Caffe 中Python使用的注意事项
- 零基础学Python注意事项(十二)——异常处理与常见异常汇总
- C程序员使用Python的注意事项
- #小练习 使用HTMLParser获取data时注意事项 分类: python 小练习 HTMLParser 2013-11-08 21:05 335人阅读 评论(0) 收藏
- python3之import和reload的使用注意事项
- 使用Ipython notebook 学习《Python for Data Analysis》 在win7下搭建注意事项
- Python中除法使用的注意事项
- python 使用plt的一些注意事项
- Python中除法使用的注意事项
- python全局变量使用注意事项_