Python 面向对象学习笔记

面向对象技术简介

类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
方法: 类中定义的函数。
类变量: 类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
数据成员: 类变量或者实例变量用于处理类及其实例对象的相关的数据。
方法重写: 如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
局部变量: 定义在方法中的变量,只作用于当前实例的类。
实例变量: 在类的声明中,属性是用变量来表示的。这种变量就称为实例变量,是在类声明的内部但是在类的其他成员方法之外声明的。
继承: 即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟"是一个(is-a)"关系(例图,Dog是一个Animal)。
实例化: 创建一个类的实例,类的具体对象。
对象: 通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。

实验

类是用于描述相同的属性和方法的对象的集合。

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# 定义一个类
class myclass:
    t=1
    # 构造方法,可以有参数,也可以无
    def __init__(self, realPart, imagPart):
        self.r = realPart
        self.i = imagPart
    def f(self):
        return 'hello hhhhhhh'
# 实例化类
x = myclass(3, -4)
# 访问类的属性和方法
print("t=", x.t, "f=", x.f())
print(x.r, x.i)
print("——————————————————")
# self代表类的实例,而非类
# 类的方法与普通函数只有一个区别——它们必须有额外的第一个参数名称,按照惯例是self
class test:
    def prt(self):
        print(self)
        print(self.__class__)
t = test()
t.prt()
# 类的方法
class people:
    # 定义类基本属性
    name = ''
    age = 0
    __weight = 0
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s speaks she is %d years old"%(self.name, self.age))
p = people('Bob', 10,30)
p.speak()

继承

Python支持类的继承,这就是类存在的意义。派生类的定义如下:

class DerivedClassName(BaseClassName1):
	<statement-1>
	.......
	<statement-N>

注意圆括号中基类的顺序,若是基类中有相同的方法名,而在子类使用时未指定,Python从左至右搜索,即方法在子类中未找到时,从左到右查找基类中是否包含方法。
BaseClassName必须与派生类定义在一个作用域内。

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s says that she is  %d years old" %(self.name,self.age))
 
#单继承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #调用父类的构函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆写父类的方法
    def speak(self):
        print("%s says that she is %d years old and in grade %d"%(self.name,self.age,self.grade))
s = student('ken',10,60,3)
s.speak()

输出结果

ken says that she is 10 years old and in grade 3

多继承

多继承的类定义如下:

class DerivedClassName(Base1, Base2, Base3……):
	<statement-1>
	.......
	<statement-N>

多继承需要注意圆括号内父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定是来自于哪一个父类,Python则从左到右依次搜索。

#类定义
class people:
    #定义基本属性
    name = ''
    age = 0
    #定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0
    #定义构造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s says that she is  %d years old" %(self.name,self.age))
# 多继承示例
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print('I am %s and my topic is %s'%(self.name, self.topic))
class sample(speaker, student):
    a = ''
    def __init__(self, n, a, w, g, t):
        student.__init__(self, n, a, w, g)
        speaker.__init__(self, n, t)
test = sample('Tim', 25, 80, 4, 'python')
test.speak()

输出结果

I am Tim and my topic is python

方法重写

父类的方法不能满足需求时,可以在子类中重写父类的方法,如下:

    class Parent:
        def myMethod(self):
            print("Print parent")
    class Child(Parent):
        def myMethod(self):
            print("Print child")
    c = Child()#define subclass
    c.myMethod()#subclass use the rewrite method
    super(Child, c).myMethod()#subclass use parent method which is covered

输出结果

Print child
Print parent

类属性与方法

__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用,不能在类的外部调用。

类的私有属性

class JustCounter:
    __secretCount= 0 #private variable
    publicCount = 0 #publi variable
    def count(self):
        self.__secretCount +=1
        self.publicCount +=1
        print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.publicCount)
print(counter.__secretCount)#error, because the instance have no right to access private variable.

1
2
2
Traceback (most recent call last):
File “py3class.py”, line 70, in
print(counter.__secretCount)#error, because the instance have no right to access private variable.
AttributeError: ‘JustCounter’ object has no attribute ‘__secretCount’
最后一句会报错,原因是实例不能访问私有变量。

类的私有方法

class site:
    def __init__(self,name, url):
        self.name = name #public
        self.__url = url #private
    def who(self):
        print('name: ',self.name)
        print('url: ',self.__url)
    def __foo(self):
        print('Private method')
    def foo(self):
        print('Public method')
        self.__foo()
x = site('runoob','www.runoob.com')
x.who()
x.foo()
x.__foo()# error, because "__foo" isprivate method

输出结果

name: runoob
url: www.runoob.com
Public method
Private method
Traceback (most recent call last):
File “py3class.py”, line 86, in
x.__foo()# error, because “__foo” isprivate method
AttributeError: ‘site’ object has no attribute ‘__foo’

类的专有方法

init_ : 构造函数,在生成对象时调用
del : 析构函数,释放对象时使用
repr : 打印,转换
setitem : 按照索引赋值
getitem: 按照索引获取值
len: 获得长度
cmp: 比较运算
call: 函数调用
add: 加运算
sub: 减运算
mul: 乘运算
truediv: 除运算
mod: 求余运算
pow: 乘方

运算符重载

Python支持运算符重载

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b =b
    def __str__(self):
        return 'Vctor (%d, %d)'%(self.a, self.b)
    def __add__(self, other):
        return Vector(self.a +other.a, self.b+other.b)
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1+v2)

输出结果

Vctor (7, 8)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值