我的Python第五篇 面向对象
来源:互联网 发布:核聚变还有多少年知乎 编辑:程序博客网 时间:2024/06/06 12:54
一、类(class)的定义
1.定义一个类
>>> class Cocacola: formula = ['caffeine','sugar','water','soda'] def drink(self): print('Energy!')>>> >>> coke_for_me = Cocacola()>>> coke_for_you = Cocacola()>>> coke_for_me.formula['caffeine', 'sugar', 'water', 'soda']>>> coke_for_me.drink()Energy!>>>
2.类的属性
在类当中赋值的变量,就是类的变量,就是类的属性。
>>> class Cocacola: formula = ['caffeine','sugar','water','soda']>>> coke_for_me = Cocacola()>>> coke_for_me.formula['caffeine', 'sugar', 'water', 'soda']
3.类的实例化
将类的定义赋予一个实例
>>> class Cocacola: formula = ['caffeine','sugar','water','soda']>>> coke_for_me = Cocacola()>>> coke_for_me.formula['caffeine', 'sugar', 'water', 'soda']
4.类属性的引用
类的实例可以引用类的属性,类的属性会被类的实例共享。类的属性可以遍历。
>>> >>> Cocacola.formula['caffeine', 'sugar', 'water', 'soda']>>> coke_for_me.formula['caffeine', 'sugar', 'water', 'soda']>>> coke_for_you.formula['caffeine', 'sugar', 'water', 'soda']>>>
>>> >>> for i in Cocacola.formula: print(i)caffeinesugarwatersoda>>> for i in coke_for_me.formula: print(i)caffeinesugarwatersoda>>>
5.实例属性
实例可以赋值新的变量,实例的变量就是实例的属性。
>>> >>> class Cocacola: formula = ['caffeine', 'sugar', 'water', 'soda']>>> coke_for_me = Cocacola()>>> coke_for_me.new_taste = 'cherry'>>> print(coke_for_me.new_taste)cherry>>>
6.实例方法
A.
>>> >>> class Person: def sport(self): print('Run!') print('Jump!')>>> xiaoming = Person()>>> xiaoming.sport() # 这里不需要输入参数Run!Jump!>>>
B.更多的参数:
>>> >>> class Beer: formula = ['Hops','Malt_dust','yeast','wather'] def drink(self,how_much): if how_much == 'a sip': print('Cool~~') elif how_much == 'whole bottle': print('Headache!')>>> Tsingtao_Beer = Beer()>>> Tsingtao_Beer.drink('a sip')Cool~~>>> Tsingtao_Beer.drink('whole bottle')Headache!>>>
8.self
被创建的实例本身,将一个对象作为一个参数放入函数中。如果类的方法中只有一个self,则类的实例引用方法时不需要再额外填入一个参数。
9.__init__()
魔术方法
初始化,可以在类中直接创建实例的方法并加以引用。
>>> >>> class Beer: formula = ['Hops','Malt_dust','yeast','wather'] def __init__(self): for element in self.formula: print('The beer has {}'.format(element))>>> Tsingtao_Beer = Beer('青岛啤酒')The beer has HopsThe beer has Malt_dustThe beer has yeastThe beer has wather>>>
二、类的继承
阅读全文
0 0
- 我的Python第五篇 面向对象
- Python之路【第五篇】:面向对象及相关
- 我的Python第五篇 函数篇
- 我的面向对象
- 面向对象--第五篇(函数的调用模式)
- python的面向对象
- 第五章 面向对象的PHP
- 我理解的面向对象
- 面向对象的python(一)
- 面向对象的python(二)
- Python面向对象的编程
- python 面向对象的编程
- Python面向对象的编程
- python面向对象的继承
- python面向对象的理解
- python的面向对象基础
- python-面向对象的基本概念
- [Language]Python的面向对象
- 正则表达式随笔
- 挑战题一(1)
- C++之 typedef
- 基于双数组Trie的词典查询算法
- 51NOD 1090 三个数和为0 【暴力 二分】
- 我的Python第五篇 面向对象
- WIN7下查看CPU核心数
- 10 request&&response的学习笔记
- Otto源码详解
- Java中CountDownLatch的使用
- Android自动化测试(UiAutomator)简要介绍
- javaScript 引用 浅拷贝 深拷贝
- Leetcode 207
- 视频做背景无法自适应屏幕的问题