python based tutorial: Python and dynamic objects are added to the class attributes and methods of operation example

This article describes the example Python and dynamic objects are added to the class properties and method of operation. Share to you for your reference, as follows:

Dynamic objects are added to a class and properties

The definition of a Person class

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

Add properties to an object

# 创建2个Person,分别为p1,p2
p1 = Person('amy')
print(p1.name)
p1.age = 10   # 给p1对象添加属性
print(p1.age)  # 输出10
p2 = Person('anne')
print(p2.name)  
p2.age = 18   # 给p2对象添加属性
print(p2.age)  # 输出18

operation result:

amy
10
anne
18

Add property to class

p1 = Person('amy')
p2 = Person('anne')
Person.sex = 'female'
print(p1.sex) # 输出 female
print(p2.sex) # 输出 female
p2.sex = 'male'
print(p2.sex) # 输出 male

operation result:

female
female
male

Dynamic objects are added to the class and method

Dynamic method of adding to the class

# 在类的外部定义一个sleep函数
p1 = Person('amy')
p2 = Person('anne')
def sleep(self):
 print('%s sleep' % (self.name))
Person.sleep = sleep
Person.sleep(p1)  # 输出 amy sleep
Person.sleep(p2)  # 输出 anne sleep

operation result:

amy sleep
anne sleep

Adding to the object method

import types # 如果是给对象动态添加方法,需要导入types模块
p = Person('amy')
def eat(self):
 print('%s eat' % (self.name))
p.eat = types.MethodType(eat, p) # 调用MethodType()函数,参数1:方法名,参数2:对象名
p.eat()    # 输出 amy eat

operation result:

amy eat

Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together progress

Published 27 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/haoxun08/article/details/104762479