Python面向对象的编程注意细节

和前文一样,这了也是学习过程中,来源于网上各种资料的一个整合记录,希望能够帮到自己和大家;

主要的关注点是在使用class的时候,应该注意的一些细节;

1.在class里面,有了 __init__(self,...)函数之后,构造对象就不能用空的参数了,相当于java里面有了构造函数之后就不能使用默认的构造函数了;

2.__init__(self,...)函数的第一个参数永远是默认的self,调用的时候不用传入;

3.python允许对象实例化以后动态的绑定任何数据,所以同一个类的不同实例可能有不同的属性:

   #对象可以随意绑定对象,所以同一个类的不同实例可以拥有不同的属性;

         Jack.age = 17
         print(Jack.age)
        #Robin对象没有属性age,下面的语句就会报错
        #print(Robin.age)

4.python里面,类中的变量如果不想被外面访问,就用 __name,__score,即在变量名字前面加上俩个下划线,但是 __name__ 这样的变量是特殊变量,是可以被访问的;

5.python是一种动态的语言,java是一种静态的语言,在多态问题上就可以看出来,python只需要调用函数的对象有同名的方法即可,不管是否是原来对象的子类;

 1 # -*- coding: utf-8 -*-
 2 
 3 'test class 多态'
 4 
 5 class Animal(object):
 6     def run(self):
 7         print("Animal is running...")
 8         
 9 class Cat(Animal):
10     def run(self):
11         print("Cat is running...")
12         
13 class Dog(Animal):
14     def run(self):
15         print('Dog is running...')
16         
17 animal = Animal()
18 cat = Cat()
19 dog = Dog()
20 animal.run()
21 cat.run()
22 dog.run()
23 
24 #判断对象的数据类型,便于理解多多态的概念
25 print(isinstance(cat, Cat))
26 #说明cat对象不仅仅是Cat的实例,也是Animal的实例;
27 print(isinstance(cat, Animal))
28 #但是Animal就不是cat 或者dog
29 print(isinstance(animal, Cat),isinstance(animal, Dog))
30 
31 #多态:编写一个函数,根据传入的对象的不同类型,调用对应的run()函数;
32 def run_twice(animal):
33     animal.run()
34     animal.run()
35     
36 run_twice(animal)
37 run_twice(cat)
38 run_twice(dog)
39 #这里只是为了说明这个动态语言的问题
40 def NotAnimal(object):
41     def run(self):
42         print('I am not a animal but i can invoke runtwice() too...')
43 notanimal = NotAnimal()
44 run_twice(notanimal)

 6.python文件的读写, 

  with open('D://path') as f:

    print(f.read())

  为了每次都能在打开文件之后关闭文件,并且让书写简单,with会自动调用f.close()

 

原文地址:https://www.cnblogs.com/robin2ML/p/6719224.html