面向对象编程基础(进阶4)

转载请标明出处:
http://www.cnblogs.com/why168888/p/6416148.html

本文出自:【Edwin博客园】


面向对象编程基础(进阶4)

1. python之面向对象编程

万物皆对象,因学过Java面向对象编程思想,Python也一样,所以简单写下这节

什么是面向对象编程

  • 面向对象编程是一种程序设计范式
  • 把程序看做不同对象的相互调用
  • 对现在世界建立对象模型

面向对象编程的基本思想

  • 类和实列
  • 类用于定义抽象类型
  • 实例根据类的定义被创建出来

2. python之定义类并创建实例

# -*- coding:utf-8 -*-
class Person(object):
    pass

xiaoming = Person()
xiaohong = Person()
print xiaoming
print xiaohong
print xiaoming == xiaohong

3. python中创建实例属性

class Person(object):
    pass
p1 = Person()
p1.name = 'Bart'

p2 = Person()
p2.name = 'Adam'

p3 = Person()
p3.name = 'Lisa'

L1 = [p1, p2, p3]
L2 = sorted(L1, lambda p1, p2: cmp(p1.name, p2.name))

print L2[0].name
print L2[1].name
print L2[2].name

4. python中初始化实例属性

在定义 Person 类时,可以为Person类添加一个特殊的__init__()方法,当创建实例时,init()方法被自动调用,我们就能在此为每个实例都统一加上以下属性

class Person(object):
    def __init__(self, name, gender, birth, **kw):
        self.name = name
        self.gender = gender
        self.birth = birth
        for k, v in kw.iteritems():
            setattr(self, k, v)
xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')
print xiaoming.name
print xiaoming.job

5. python中访问限制

Python对属性权限的控制是通过属性名来实现的,如果一个属性由双下划线开头(__),该属性就无法被外部访问。

class Person(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score

p = Person('Bob', 59)

print p.name
print p.__score

6. python中创建类属性

每个实例各自拥有,互相独立,而类属性有且只有一份。

class Person(object):
    count = 0
    def __init__(self, name):
        Person.count = Person.count + 1
        self.name = name
p1 = Person('Bob')
print Person.count # 1

p2 = Person('Alice')
print Person.count # 2

p3 = Person('Tim')
print Person.count # 3

7. python中类属性和实例属性名字冲突怎么办

class Person(object):
    __count = 0
    def __init__(self, name):
        Person.__count = Person.__count + 1
        self.name = name
        print Person.__count

p1 = Person('Bob')
p2 = Person('Alice')

print Person.__count

8. python中定义实例方法

class Person(object):

    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def get_grade(self):
        if self.__score >= 80:
            return 'A'
        if self.__score >= 60:
            return 'B'
        return 'C'

p1 = Person('Bob', 90)
p2 = Person('Alice', 65)
p3 = Person('Tim', 48)

print p1.get_grade()
print p2.get_grade()
print p3.get_grade()

9. python中方法也是属性

class Person(object):

    def __init__(self, name, score):
        self.name = name
        self.score = score
        self.get_grade = lambda: 'A'

p1 = Person('Bob', 90)
print p1.get_grade
print p1.get_grade()

10. python中定义类方法

和属性类似,方法也分实例方法和类方法。

class Person(object):
    __count = 0
    @classmethod
    def how_many(cls):
        return cls.__count
    def __init__(self, name):
        self.name = name
        Person.__count = Person.__count + 1

print Person.how_many()
p1 = Person('Bob')
print Person.how_many()
原文地址:https://www.cnblogs.com/why168888/p/6416148.html