Python基础(三)

这里主要将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 = 10
print(apple.price)

banana = Fruit('banana', 'yellow')
print(banana.price)
banana.price = 20
print(banana.price)

Fruit.price = 100
orange = Fruit('orange', 'orange')
print(orange.price)
orange.price = 30
print(orange.price)

输出结果

0
10
0
20
100
30

上述结果说明,对于类变量来说,当创建一个对象的时候,会将类变量拷贝一份给对象,每个对象都独立的拥有类变量,修改各个对象类变量的时候,互不影响。如果通过类修改类变量,那么以后创建的类的类变量,均是修改后的值。

__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 = 100

Fruit.grow_1()
print(Fruit.price)
Fruit.grow_2()
print(Fruit.price)

类方法和静态方法皆可以访问类的静态变量(类变量),但不能访问实例变量。
但两者实现方式不同。类方法传递了一个参数cls,和self类似,self指传递过来的对象,cls指传递过来的类。所有,类方法通过cls.访问,静态方法通过类名加.访问。

调用父类构造函数

python中,子类不会自动调用父类构造函数,除非显示的调用。调用有两种方法

class A:
    pass

class 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值