关于Python中面向对象
什么是面向对象
这可能对于很多初学者来说是个问题,关于面向对象和面向过程可以说一直是编程界的两大阵营吧,没有好与坏之分,全在于个人见解吧,但是不得不说,现在面向过程更加主流一些吧!
面向对象的语言很多,最典型应该算Java吧!而面向过程的语言也很多,代表应该就是C语言了,但同时,又有许多的语言为了照顾这两方面的人,既支持面向过程,又支持面向对象,而Python就是这种类型。
简单来说,面向过程就是在写代码的时候,注重的是实现目的的过程是什么方式的,这个过程是怎样的,通过什么样的步骤可以解决掉他。而面向对象是对整体的考虑,将万物看作类,不同的物品通过不同的类封装,一个类里面,有类自己的属性,方法等。python支持面向对象和面向过程,一般对与比较小的项目,可以使用面向过程的方法实现比较简单,而大型项目就需要定义不同的类,在每个类里面再进行具体方法的实现。
关于类与类的实例,我举个例子吧,水果和苹果的例子,水果就是一个类,而苹果就是水果的一个实例,我们在吃苹果时说是吃水果,但是我们不能只吃水果,我们吃的,一定是水果的一个实例。请大家仔细品味这句话。
怎样创建一个类?
class classs_name(object):
pass
关于一些重要的方法
关于__init__方法
关于__new__方法
class test(object):
def __init__(self):
print "__init__ was called "
def __new__(cls):
print "__new__ was called"
return super(test,cls).__new__(cls)
__new__ was called
__init__ was called
class test(object):
def __init__(self):
print "__init__ was called "
def __new__(cls):
print "__new__ was called"
#return super(test,cls).__new__(cls)
__new__ was called
关于__del__方法
class test(object):
def __init__(self):
print "__init__ was called"
def __del__(self):
print "__del__ was called"
t=test()
b=test()
t1=t
t2=t
print(id(t))
print(id(t1))
print(id(t2))
print('del t')
del t
print('del t1')
del t1
print('del t2')
del t2
print('del b')
del b
__init__ was called
139872429641488
139872429641488
139872429641488
del t
del t1
del t2
__del__ was called
del b
__del__ was called
继承,封装,多态——面向对象三大特征
继承
封装
多态
class Animal(object):
def run(self):
print("Animal is running")
class Dog(Animal):
pass
class Cat(Animal):
pass
d=Dog()
c=Cat()
d.run()
c.run()
Animal is running
Animal is running
class Animal(object):
def __init__(self):
self.__name='Animal'
self.age=5
class Dog(Animal):
pass
d=Dog()
print(d.age)
print(d.__name)
5
Traceback (most recent call last):
File "class.py", line 9, in <module>
d.__name
AttributeError: 'Dog' object has no attribute '__name'
class Animal(object):
def run(self):
print("Animal is running")
class Dog(Animal):
def run():
print "Dog is running"
class Cat(Animal):
def run():
print "Cat is running"
d=Dog()
c=Cat()
d.run()
c.run()
Dog is running
Cat is running
实例属相和类属性
class Soft(object):
version=0.1 #创建一个类属性version
s=Soft()
print(Soft.version) # 因为version为类属性,所以应该通过类名点来访问
print(s.version) # 按上面所讲的,类属性通过实例来访问应该是报错的,但是python实现是先在实例属性中检索,然后再到类属性中去检索,所以最终是可以访问到的,并且不会报错。
Soft.version+=1 # 改变类属性的值
print(Soft.version) # 通过类名点访问
print(s.version) # 通过实例来访问
s.version=1.0 # 注意,类属性只能通过类名点访问,此操作是建立了一个名为version的实例属性
print(Soft.version)
print(s.version)
0.1
0.1
1.1
1.1
1.1
1.0