1. 基本概念
首先要明确要明确一下,python中实例方法、类方法和静态方法的区别, 先看一个简单的类:
class Person():
# class property
__num = 0
def __init__(self, name="NoName", age=0):
self.name = name;
self.age = age;
def __new__(cls):
cls.__num += 1
@staticmethod
def move():
print("I am moving")
#self.printPerson()
def printPerson(self):
print("I am {}, and I am {} years old".format(self.name, self.age))
self.move()
@classmethod
def getInstanceCount(cls):
return cls.__num
a. 实例方法,第一个参数必须为实例对象,该参数名称一般约定为self。如 printPerson(self)
通过它传递实例的属性和方法,也可以传递类的属性和方法(因为类的属性和方法也可以被实例调用).
调用:他只能由实例对象调用。
b. ;类方法。使用装饰器@classmethod进行定义, 如addCount(cls)
。 第一个参数必须是当前类对象,该参数名一般约定为“cls”,通过他来传递类的属性和方法(一般不传实例的属性和方法)
调用:实例和对象都可以调用。
c. 静态方法。使用装饰器@staticmethod, 如move()。参数随意,没有self和cls参数,但是方法体中不能使用类或实例的任何属性和方法。可以理解为,静态方法是个独立的、单纯的函数,它仅仅托管于某个类的名称空间中,便于使用和维护。
2. 代码演示
- 动态增加成员
class Person():
def __init__(self, name="NoName", age=0):
self.name = name;
self.age = age;
def printPerson(self):
print("I am {}, and I am {} years old".format(self.name, self.age))
实例化对象后,可以添加成员
a = Person()
a.sex = "Boy"
a.sex
- 增加静态方法
@staticmethod
def hello():
#? how to use the data of Person
print("Hi, there")
Person.hello = hello
调用
a = Person()
a.hello()
- 动态添加类方法
@classmethod
def myDynClassMethod(cls):
print("I am dynamic class method")
调用
Person.hello = hello
Person.dynClassMethod = myDynClassMethod
输出: I am dynamic class method