之前很少写过面向对象编程,所以很多概念当时学的时候了解,但是不久就忘了。现在自己重新整理一下比较重要的概念。
1,__init__这是python里面比较特殊的方法,在定义类后,如果加上了__init__方法那么在创建实例的时候需要把__init__需要的属性跟着传进来。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
__init__方法的第一个变量永远是self。有了这个方法后再创建实例就不能传空的参数了,需要把init需要的参数跟着传进来。
2,__双下划线,在上面定义的变量在生成实例后可以更改,如果不想让他们被外部访问的话,可以在属性名称前面加上__,这样就变成了私有变量。外部不能访问更改了。
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
>>> bart = Student('Bart Simpson', 59)
>>> bart.__name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__name'
3,_单下划线,在属性前面加上_后就会阻止其他python脚本通过【from module import *】语句导入该名字,即该名字不会被星号匹配。
4,类的继承,继承的好处就是子类拥有了父类的全部功能,还可以在子类下面增加新的方法。
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Eating meat...')
在子类与父类都有同一个方法时会调用子类的方法。
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
这里在Dog类中调用run方法时会显示 Dog is running...而不是Animal is running...。
在我们定义一个class的时候,我们实际上是定义了一种数据类型。这个定义的数据类型和list,str等数据类型没有区别。它可以作为一个变量传入函数中。且该函数可以使用对象中的方法。
def run_twice(animal):
animal.run()
animal.run()
>>> run_twice(Animal())
Animal is running...
Animal is running...
5,__call__,也是python中类的内置方法。具体用法是在直接调用类的时候会把参数传到__call__方法里面去,并且执行这个方法。例如下
class Person:
def __call__(self , name):
print('__call__'+'Hello'+name)
def hello(self , name):
print('hello'+ name)
person = Person()
person('zhangsan')
person.hello('list')
它的输出为
__call__Hellozhangsan
hellolist