您的位置:首页 > 编程语言 > Python开发

廖雪峰python学习笔记8:面向对象初步

2016-07-12 10:22 537 查看
#! /usr/bin/env python3
# -*- coding: utf-8 -*-

#创建对象与多态:
class Animal(object):
def run(self):
print('Animal is running')

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

class Tortoise(Animal):
def run(self):
print('Tortoise is running slowly')
#定义一个函数
def run_twice(animal):
animal.run()
animal.run()

aa = Animal()
dd = Dog()
tt = Tortoise()

run_twice(aa)
run_twice(dd)
run_twice(tt)

#和java,c++等静态语言不同的是:
class Timer(object):
def run(self):
print('Timer is running')

ttt = Timer()
run_twice(ttt)  #纳尼?这样也可以用
#这就是动态语言的“鸭子类型”,它并不要求严格的继承体系
#一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。

#使用type()
#当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
print(type(123))
a = Animal()
print(a)

#对于class的继承关系来说,使用type()就很不方便。
#我们要判断class的类型,可以使用isinstance()函数。
b = Dog()
print(isinstance(b, Animal))  #返回一个布尔型常量来判断b是否为Animal,这里返回True

#使用dir()来获得一个对象的所有属性和方法
b.name = 'NANCY'
print(dir(b))

#python可以自由地给一个实例变量绑定属性
class Student(object):
pass
bart = Student()

bart.name = 'name'
print(bart.name)

#由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。
#通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去

class Teacher(object):
def __init__(self, name = 'Leo', score = 100):
self.name = name
self.score = score

def print_score(self):
print('%s: %s' % (self.name, self.score))

tea = Teacher()
tea.print_score();
#__init__方法的第一个参数永远是self,表示创建的实例本身
#因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。

#访问限制,like private

class Person(object):
def __init__(self, name = 'Leo', age = 19):
self.__name = name
self.__age = age
def print_person(self):
print('%s: %d' % (self.__name, self.__age))
def set_age(self,age):
self.__age = age
leo = Person()
leo.print_person()
leo.age = 18 #age已经无法从外部访问
#可以这样修改
leo.set_age(18)
leo.print_person()
#Attention: It't different between __name and name

#Pyhthon是动态语言,但是,如果像C++那样,Student类本身需要绑定一个属性呢?
class man(object):
name = 'NAME'
s = man()
print(s.name)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python