Python基础(三)
来源:互联网 发布:淘宝开店案例 编辑:程序博客网 时间:2024/06/11 17:53
这里主要将python的面向对象编程技术。
类和对象
类是对客观世界食物的抽象,而对象是类实例化后的实体。比如,水果是一个类,将其实例化为苹果,则苹果就是一个对象。
类的定义
class Fruit(): def __init__(self, name, color): self.name = name self.color = color def grow(self): print('The fruit id growing...')
定义了一个类叫Fruit,__inti__
为类的构造函数。
对象的创建
对象的创建过程就是累的实例化过程。
apple = Fruit('apple', 'red')
创建了Fruit类的一个对象apple。
类变量和成员变量
class Fruit(): price = 0 #类变量 def __init__(self, name, color): self.name = name #成员变量 self.color = color #成员变量 def grow(self): print('The fruit id growing...')apple = Fruit('apple', 'red')print(apple.price)apple.price = 10print(apple.price)banana = Fruit('banana', 'yellow')print(banana.price)banana.price = 20print(banana.price)Fruit.price = 100orange = Fruit('orange', 'orange')print(orange.price)orange.price = 30print(orange.price)
输出结果
01002010030
上述结果说明,对于类变量来说,当创建一个对象的时候,会将类变量拷贝一份给对象,每个对象都独立的拥有类变量,修改各个对象类变量的时候,互不影响。如果通过类修改类变量,那么以后创建的类的类变量,均是修改后的值。
在__init__
函数中初始化的变量,叫做成员变量。由于python是动态语言,可以随时添加成员变量
class Fruit(): def __init__(self, name, color): self.name = name self.color = color def grow(self): self.grow = 'grow' #添加的成员变量 print('The fruit id growing...')
类变量可以通过对象,类访问,成员变量只能通过对象访问。
类方法和成员方法
class Fruit(): price = 0 def __init__(self, name, color): self.name = name self.color = color def grow(self): #成员方法 print('The fruit id growing...') @staticmethod def grow_1(): #静态方法 print('This is static method') Fruit.price = 50 @classmethod def grow_2(cls): #类方法 print('This is class method') cls.price = 100Fruit.grow_1()print(Fruit.price)Fruit.grow_2()print(Fruit.price)
类方法和静态方法皆可以访问类的静态变量(类变量),但不能访问实例变量。
但两者实现方式不同。类方法传递了一个参数cls
,和self
类似,self
指传递过来的对象,cls
指传递过来的类。所有,类方法通过cls
加.
访问,静态方法通过类名加.
访问。
调用父类构造函数
python中,子类不会自动调用父类构造函数,除非显示的调用。调用有两种方法
class A: passclass B(A): def __init__(self): A.__init__(self)class C(A): def __init__(self): super(C, self).__init__()
这两种调用方法是有区别的,主要体现在多继承上,详见Python中既然可以直接通过父类名调用父类方法为什么还会存在super函数?-知乎
变量初始化
如果找不到合适数据类型来初始化,可使用None来初始化
x = None
阅读全文
0 0
- Python 基础(三)
- Python基础(三)
- Python基础(三)
- python基础(三)
- Python基础语法(三)
- Python 基础拾遗(三)
- Python 基础语法(三)
- Python 基础回顾(三)
- Python入门基础(三)
- Python基础课程(三)
- Python入门基础(三)
- Python基础(三)-变量
- python基础练习(三)
- python基础(三)tuple
- Python基础学习(三)
- Python基础语法(三)
- 自学Python之Python基础:(三)Python代码结构
- Python 基础编程 -- 字符串 (三)
- python编写一个函数,输入n为偶数时,调用函数求1 / 2 + 1 / 4 + ... + 1 / n, 当输入n为奇数时,调用函数1 / 1 + 1 / 3 + ... + 1 / n(指针函数
- 【排序算法】:选择排序
- “区块链”究竟是什么鬼
- Leetcode-Remove element-Python
- python入门(九):集合及其运算
- Python基础(三)
- Sublime Text的配置
- WP Super Cache 安装与设置详解
- 常见排序算法及其C语言实现(二)
- RecyclerView 之通用适配
- 动态规划基本问题
- 编写Java程序,显示五个加减法测验的正确率和用时
- 动态规划(三.LCS)
- intent的使用