Python实现动态添加属性和方法操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现动态添加属性和方法操作。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#!python3
class Person():
  def __init__(self, name, age):
    self.name = name
    self.age = age
p1 = Person('ff', '28')
print(p1.name, p1.age)
# 给实例对象动态添加sex属性
p1.sex = 'female'
print(p1.sex)
# 给类动态添加属性
Person.height = None
print(Person.height)
p1.height = '155'
print(p1.height)
# 动态定义一个方法
def run(self, speed):
  print('run with %d speed' % speed)
# 给实例绑定方法
import types
p1.run = types.MethodType(run, p1)
p1.run(30)
# Person.run = run # 运行错误 
# Person.run(4)
@classmethod
def run2(a, speed):
  print('run with %d m/s' % speed)
# 给类动态绑定方法
Person.run2 = run2    # 给类绑定的方法, 需加修饰器 @classmethod, 标定其为类方法,可被类添加
Person.run2(4)
p1.run2(5)       # 类的实例对象也可调用类动态添加的方法
@staticmethod
def eat():
  print('eat---')
Person.eat = eat    # 类可添加静态方法, 定义静态方法时,需加修饰器@staticmethod
Person.eat()
p1.eat()        # 实例对象同样可调用类动态添加的静态方法
del p1.name       # del 删除属性
delattr(p1, 'sex')
print(p1.name, p1.sex)

运行结果:

ff 28
female
None
155
run with 30 speed
run with 4 m/s
run with 5 m/s
eat---
eat---
Traceback (most recent call last):
  File "/home/python/Desktop/test/12_动态语言.py", line 41, in <module>
    print(p1.name, p1.sex)
AttributeError: 'Person' object has no attribute 'name'

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

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

相关文章

利用Psyco提升Python运行速度

Psyco 是严格地在 Python 运行时进行操作的。也就是说,Python 源代码是通过 python 命令编译成字节码的,所用的方式和以前完全相同(除了为调用 Psyco 而添加的...

简单总结Python中序列与字典的相同和不同之处

共同点: 1.它们都是python的核心类型,是python语言自身的一部分 核心类型与非核心类型 多数核心类型可通过特定语法来生成其对象,比如"dave"就是创建字符串类型的对象的...

使用python实现tcp自动重连

操作系统: CentOS 6.9_x64 python语言版本: 2.7.13 问题描述 现有一个tcp客户端程序,需定期从服务器取数据,但由于种种原因(网络不稳定等)需要自动重连。 测...

python3 实现的对象与json相互转换操作示例

本文实例讲述了python3 实现的对象与json相互转换操作。分享给大家供大家参考,具体如下: 1. python主要有三种数据类型:字典、列表、元组,其分别由花括号,中括号,小括号表...

django fernet fields字段加密实践详解

一、fernet介绍 Fernet 用于django模型字段对称加密,使用 crytography 库。 官网帮助文档 1、先决条件 django-fernet-fields 支持D...