这里主要将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