zhuyumu 发表于 2015-12-15 09:02:49

python杂记(二)

1、函数
    def sum(a,b):
      c=a+b
      return c
    print(sum(1,2))

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))
    注意到__init__方法的第一个参数永远是self,表示创建的实例本身

3、面向对象权限
    实例的变量名如果以__开头,就变成了一个私有变量(private)
    如果外部代码要获取name和score怎么办?可以给Student类增加get_name和get_score这样的方法:
    class Student(object):
    ...
    def get_name(self):
      return self.__name
    def get_score(self):
      return self.__score
    def set_score(self, score):
      self.__score = score

4、继承与多态
    class Animal(object):
    def run(self):
      print('Animal is running...')

    class Dog(Animal):
      def run(self):
            print('Dog is running...')

    class Cat(Animal):
      def run(self):
            print('Cat is running...')

5、获取对象信息
    判断对象类型,使用type()函数,如:print(type(123)) # 获取123的类型
    isinstance()判断一个对象是否是某种类型
    'ABC'.lower() #ABC转为小写

   
页: [1]
查看完整版本: python杂记(二)