python 教程 第九章、 类与面向对象

简介: 第九章、 类与面向对象 1)    类 基本类/超类/父类被导出类或子类继承。 Inheritance继承 Inheritance is based on attribute lookup in Python (in X.

第九章、 类与面向对象
1)    类
基本类/超类/父类被导出类或子类继承。
Inheritance继承
Inheritance is based on attribute lookup in Python (in X.name expressions).
Polymorphism多态
In X.method, the meaning of method depends on the type (class) of X.
Encapsulation封装
Methods and operators implement behavior; data hiding is a convention by default.

class C1():
    def __init__(self, who):
        self.name = who
I1 = C1('bob')
print I1.name #bob 

2)    命名空间

X = 11              # Global (module) name/attribute (X, or manynames.X)
def f():
    print(X)        # Access global X (11)
def g():
    X = 22          # Local (function) variable (X, hides module X)
    print(X)
class C:
    X = 33          # Class attribute (C.X)
    def m(self):
        X = 44      # Local variable in method (X)
        self.X = 55 # Instance attribute (instance.X) 
 
print(X)          # 11: module (manynames.X outside file)
f()               # 11: global
g()                   # 22: local
print(X)         # 11: module name unchanged
obj = C()         # Make instance
print(obj.X)      # 33: class name inherited by instance
obj.m()           # Attach attribute name X to instance now
print(obj.X)      # 55: instance
print(C.X)        # 33: class (a.k.a. obj.X if no X in instance)
#print(C.m.X)     # FAILS: only visible in method
#print(g.X)       # FAILS: only visible in function 

3)    Self参数
指向对象本身

4)    __init__构造器
如果没有__init__,则需要自己定义并赋值

class C1():                # Make and link class C1
    def setname(self, who):      # Assign name: C1.setname
        self.name = who          # Self is either I1 or I2
I1 = C1()                        # Make two instances,

#没有__init__,实例就是个空的命名空间

I1.setname('bob')                # Sets I1.name to 'bob'
print(I1.name)                   # Prints 'bob'

构造器,创建时例时自动调用。

5)    继承搜索的方法
An inheritance search looks for an attribute first in the instance object, then in the class the instance was created from, then in all higher superclasses, progressing from the bottom to the top of the object tree, and from left to right (by default).

6)    一个例子

class AttrDisplay:
    def gatherAttrs(self):
        attrs = []
        for key in sorted(self.__dict__):
            attrs.append('%s=%s' % (key, getattr(self, key)))
        return ', '.join(attrs)
    def __str__(self):
        return '[%s: %s]' % (self.__class__.__name__, self.gatherAttrs()) 
 
class Person(AttrDisplay): #Making Instances
    def __init__(self, name, job=None, pay=0): # Add defaults
        self.name = name # Constructor takes 3 arguments
        self.job  = job  # Fill out fields when created
        self.pay  = pay  # self is the new instance object
    def lastName(self):     # Assumes last is last
        return self.name.split()[-1]
    def giveRaise(self, percent):   # Percent must be 0..1
        self.pay = int(self.pay * (1 + percent)) 
 
class Manager(Person):
    def __init__(self, name, pay):
        Person.__init__(self, name, 'mgr', pay)
    def giveRaise(self, percent, bonus=.10):
        Person.giveRaise(self, percent + bonus) 
 
if __name__ == '__main__': # Allow this file to be imported as well as run/tested
    bob = Person('Bob Smith')
    sue = Person('Sue Jones', job='dev', pay=100000)
    print(bob)
    print(sue)
    print(bob.lastName(), sue.lastName())
    sue.giveRaise(.10)
    print(sue)
    tom = Manager('Tom Jones', 50000)
    tom.giveRaise(.10)
    print(tom.lastName())
    print(tom) 
相关文章
|
28天前
|
JSON C语言 C++
【Python 基础教程 26】Python3标准库全面入门教程:一步步带你深入理解与应用
【Python 基础教程 26】Python3标准库全面入门教程:一步步带你深入理解与应用
60 1
|
28天前
|
编译器 测试技术 C++
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
【Python 基础教程 01 全面介绍】 Python编程基础全攻略:一文掌握Python语法精髓,从C/C++ 角度学习Python的差异
157 0
|
28天前
|
存储 安全 API
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
73 0
|
2天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
22 0
|
2天前
|
索引 Python
python 格式化、set类型和class类基础知识练习(上)
python 格式化、set类型和class类基础知识练习
20 0
|
3天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
24天前
|
Python
Python类(class)中self的理解
Python类(class)中self的理解
17 0
|
24天前
|
Python
Python类与对象:深入解析与应用
本文介绍了Python中的核心概念——类和对象,以及它们在面向对象编程中的应用。类是用户定义的类型,描述具有相同属性和行为的对象集合;对象是类的实例,具备类的属性和方法。文章通过示例讲解了如何定义类、创建及使用对象,包括`__init__`方法、属性访问和方法调用。此外,还阐述了类的继承,允许子类继承父类的属性和方法并进行扩展。掌握这些概念有助于提升Python编程的效率和灵活性。
|
28天前
|
存储 算法 数据挖掘
【Python 基础教程 25】全面入门指南:深度解析Python3的命名空间,作用域及变量使用教程
【Python 基础教程 25】全面入门指南:深度解析Python3的命名空间,作用域及变量使用教程
50 0
|
28天前
|
存储 机器学习/深度学习 数据安全/隐私保护
【Python 基础教程 24】全面入门Python面向对象编程:深度探索与实战教程
【Python 基础教程 24】全面入门Python面向对象编程:深度探索与实战教程
76 0

热门文章

最新文章