python封装举例_Python面向对象之类的封装操作示例

本文实例讲述了Python面向对象之类的封装操作。分享给大家供大家参考,具体如下:

承接上一节《Python面向对象之类和实例》,学了Student类的定义及实例化,每个实例都拥有各自的name和score。现在若需要打印一个学生的成绩,可定义函数 print_score()

该函数为类外的函数,如下:

class Student(object):

def __init__(self, name, score):

self.name = name

self.score = score

May = Student("May",90) # 须要提供两个属性

Peter = Student("Peter",85)

print(May.name, May.score)

print(Peter.name, Peter.score)

def print_score(Student): # 外部函数print_score(Student)

# print("%s's score is: %d" %(Student.name,Student.score)) # 普通 print 写法

print("{0}'s score is: {1}".format(Student.name,Student.score)) # 建议使用 Python 2.7 + .format优化写法

print_score(May)

print_score(Peter)

既然Student实例本身就拥有这些数据,要访问这些数据,就没有必要从外面的函数去访问,我们可以直接在Student类的内部定义访问数据的函数。这样,就把数据给“封装”起来了。

“封装”就是将抽象得到的数据和行为(或功能)相结合,形成一个有机的整体(即类);封装的目的是增强安全性和简化编程,使用者不必了解具体的实现细节,而只是要通过外部接口,一特定的访问权限来使用类的成员。

而这些封装数据的函数是和Student类本身是关联起来的,我们称之为类的方法。那如何定义类的方法呢?

就要用到对象 self 本身,参考上例,把 print_score() 函数写为类的方法(Python2.7之后的版本,推荐.format 输出写法):

class Student(object):

def __init__(self, name, score):

self.name = name

self.score = score

def print_score(self):

print("{self.name}'s score is: {self.score}".format(self=self)) # Python 2.7 + .format优化写法

May = Student("May",90)

Peter = Student("Peter",85)

定义类的方法:除了第一个参数是self外,其他和普通函数一样。

实例调用方法:只需要在实例变量上直接调用,除了self不用传递,其他参数正常传入;注意,若类的方法仅需要self,不需要其他,调用该方法时,仅需 instance_name.function_name()

这样一来,我们从外部看Student类,就只需要知道,创建实例需要给出name和score,而如何打印,都是在Student类的内部定义的,这些数据和逻辑被“封装”起来了,调用很容易,但却不用知道内部实现的细节。

封装的另一个好处是可以给Student类增加新的方法;这边的方法也可以要求传参,如新增定义compare 函数,如下:

class Student(object):

def __init__(self, name, score):

self.name = name

self.score = score

def print_score(self):

print("{self.name}'s score is: {self.score}".format(self=self)) # Python 2.7 + .format优化写法

def compare(self,s):

if self.score>s:

print("better than %d" %(s))

elif self.score==s:

print("equal %d" %(s))

else:

print("lower than %d" %(s))

May = Student("May",90)

Peter = Student("Peter",85)

May.print_score()

Peter.print_score()

May.compare(100)

May.compare(90)

May.compare(89)

希望本文所述对大家Python程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当涉及到大型软件项目时,面向对象编程(OOP)比面向过程编程(POP)更具优势。以下是一些OOP相对于POP的优势: 1. 封装:OOP允许将数据和函数捆绑在一起以创建类。封装使得代码更加安全,同时也提供了更好的抽象和代码重用。这个特性可以帮助我们控制数据的访问和修改。 以下是一个使用类和封装示例代码: ```python class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: print("Insufficient balance") account = BankAccount(1000) account.deposit(500) account.withdraw(200) print(account.balance) ``` 上述代码中,我们创建了一个名为BankAccount的类,并定义了三个方法:__init__、deposit和withdraw。这个类允许我们使用封装来隐藏余额和其他数据。我们可以通过调用deposit和withdraw方法来修改余额,但无法直接访问余额。 2. 继承:OOP中的继承允许我们创建一个新的类,它从现有的类派生而来。这使得我们可以重用现有的代码并创建更具抽象性的类。 以下是一个使用继承的示例代码: ```python class Animal: def __init__(self, name): self.name = name def speak(self): pass class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" animals = [Dog("Rufus"), Cat("Whiskers"), Dog("Buddy")] for animal in animals: print(animal.name + ": " + animal.speak()) ``` 上述代码中,我们创建了一个名为Animal的基类,并定义了一个方法speak。然后,我们创建了两个继承Animal的子类Dog和Cat,并重写了speak方法。最后,我们创建了一个包含不同类型动物的列表,并使用循环打印每个动物的名称和它们的声音。 3. 多态:OOP允许多态,即对同一方法的调用可以根据对象类型的不同而产生不同的行为。这使得代码更加灵活和可扩展。 以下是一个使用多态的示例代码: ```python class Shape: def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius shapes = [Rectangle(5, 10), Circle(7), Rectangle(3, 6)] for shape in shapes: print("Area:", shape.area()) ``` 上述代码中,我们定义了一个名为Shape的基类,并定义了一个方法area。然后,我们创建了两个子类Rectangle和Circle,并重写了area方法。最后,我们创建了一个包含不同形状的列表,并使用循环打印每个形状的面积。 这些是OOP相对于POP的一些优势。虽然具体情况可能会有所不同,但在大型软件项目和复杂问题解决方案中,OOP通常是更好的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值