目录
使用staticmethod()定义静态方法 (Define static method using staticmethod())
使用@staticmethod定义静态方法 (Define static method using @staticmethod)
40.
题目:将一个数组逆序输出
思路:用第一个与最后一个交换
"""
CSDN : heart_6662
PYTHON amateur
"""
if __name__ == '__main__':
a = [9,6,5,4,1]
n = len(a)
print(a)
for i in range(len(a)//2):
a[i],a[n-i-1] = a[n-i-1],a[i]
print(a)
41.
题目:模仿静态变量的用法
1。实例变量属于某个对象的属性,必须创建了实例对象,其中的实例变量才会被分配空间,才能使用这个实例变量。静态变量不属于某个实例对象,而是属于类,所以也称为类变量,只要程序加载了类的字节码,不用创建任何实例对象,静态变量就会被分配空间,静态变量就可以被使用了总之,实例变量必须创建对象后才可以通过这个对象来使用,静态变量则可以直接使用类名来引用。
2.静态变量是包含此变量的类一旦被编译就分配了空间且之后地址不变,而实例变量在类实例化之后才分配空间,每实例化一次他就分配一次空间,所以静态变量不需要类实例化就可以用,而实例变量不可以
使用staticmethod()
定义静态方法 (Define static method using staticmethod()
)
"""
CSDN : heart_6662
PYTHON amateur
"""
class Shape:
def info(msg):
# show custom message
print(msg)
print("This class is used for representing different shapes.")
# create info static method
Shape.info = staticmethod(Shape.info)
Shape.info("Welcome to Shape class")
使用@staticmethod
定义静态方法 (Define static method using @staticmethod
)
class Shape:
@staticmethod
def info(msg):
# show custom message
print(msg)
print("This class is used for representing different shapes.")
Shape.info("Welcome to Shape class")