详解Python类与对象(上)

前言

面试官:什么是类?你:我这个人很实在,不知道什么叫累。面试官:恭喜你,你被录取了。

开个玩笑啊,对于Python或者其他面向对象的语言来说,类与对象是我们绕不开的话题,而且相比于其他基础性语法,类与对象更加复杂,难学。本文将详细讲解类与对象的概念,使用方法,希望能对读者有所帮助。

基本概念

首先我们来看看面向对象的相关名词及相关解释。

  • 类:一群有着相似性的事物的集合,这里对应 Python 的 class。

  • 对象:集合中的一个事物,这里对应由 class 生成的某一个 实例(object)。

我们首先来举个简单的例子,动物是类,那狗、猫就是动物这个类的两个实例。

  • 属性:类似于变量,用来存储数据。

  • 方法:类似于函数,用来使用数据。

例如,动物都会有毛发颜色(属性),发出叫声的能力(方法)。

初体验

看完了基本概念,如果你还一知半解的话,没有关系,我们从Python中我们最常用的int类型出发,对面向对象来一个初体验。

i = 23
type(i)

<class 'int'>

我们这里的i其实就是int类的一个实例(或者叫对象),实例一般都有属性和方法,我们可以用dir来查看。

i = 1
print(dir(i))

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

这里总共有三种类型,第一种是前带两个下划线后带两个下划线的(魔法方法);第二种就是属性;第三种就是方法。属性和方法在这里是看不出来的。

i = 1
print(i.numerator)
print(i.bit_length())

1
1

调用属性不需要加括号,方法需要加括号,这很好理解,我们如果使用过函数就明白了。

以此类推,我们常用的列表字典等数据类型,也是一样的,大家也可以自己尝试用一用。

小试牛刀

我们再来看看上面我们举的案例,动物这个类,有属性和方法,本节我们就来实现这个类,我们先来看代码。

class Animal:

    def __init__(self, species, furcolor):
        self.species = species
        self.furcolor = furcolor
        print('create')

    def call(self):
        return '{} is calling'.format(self.species)


cat = Animal('cat', 'yellow')
dog = Animal('dog', 'gray')
print(cat.furcolor)
print(dog.call())

create
create
yellow
dog is calling

(1)定义类,需要用关键词class,类名词首字母大写。

(2)__init__是构造函数,实例化(生成对象)的时候,也就是cat = Animal('cat', 'yellow')的时候,就会直接调用该方法。第一个参数必须为self,表示创建对象本身。

(3)call函数参数也为self,是为了使用自身的属性。调用的时候是使用对象.方法,当然也可以用类.方法(对象)。例如,arr.sum(),np.sum( arr )是一样的效果。

类变量

我们之前定义的变量都是对象的,我们本节定义类变量,例如动物的腿的个数。

class Animal:

    leg = 4

    def __init__(self, species, furcolor):
        self.species = species
        self.furcolor = furcolor

    def call(self):
        return '{} is calling'.format(self.species)


bird = Animal('bird', 'yellow')
dog = Animal('dog', 'gray')
print(bird.leg)
print(dog.leg)

4
4

需要注意的是,如果改变类变量,对象变量都会发生变化,如果改变的是对象变量,则类变量不发生改变。

bird = Animal('bird', 'yellow')
dog = Animal('dog', 'gray')
bird.leg = 2
print(bird.leg)
print(dog.leg)
print(Animal.leg)

Animal.leg = 6
print(bird.leg)
print(dog.leg)
print(Animal.leg)

2
4
4
2
6
6

今天的分享就到这了,下期我们将更加深入了解Python的类与对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值