类方法、静态方法

# 类方法:
class
B: country = 'China' # 静态变量(属性,字段) def func(self): # 动态普通方法 pass def __init__(self,name,age): # 特殊方法:双下方法 self.name = name @classmethod # 类方法 def func2(cls): # print(cls) cls.area = '东北' cls.name = '狗哥' print(B) print(B.__dict__) B.func2() print(B.__dict__)

 # 练习:检测一下我示例化了多少个对象。

# 类方法:必须通过类的调用,而且此方法的意义:就是对类里面的变量或者方法进行修改添加。
class C:
    count = 0
    def __init__(self):
        C.cou()

    @classmethod
    def cou(cls):
        cls.count += 1
#
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
obj = C()
print(C.count) #11

# 静态方法:

# 静态方法: 就是一个不依赖类以及对象的一个普通函数,为什么在类里面?
# 为了保证代码的一致性,可调控性,整洁性。

举个例子:
class C:
    def __init__(self):
        pass

    @staticmethod
    def func(*args, **kwargs):
        print(666)

def func(*args, **kwargs):
    print(555)
C.func()
c1 = C()
c1.func()

import time
class TimeTest(object):
    def __init__(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second
    # 各种方法


    @staticmethod # 静态方法
    def showTime():
        return time.strftime("%H:%M:%S", time.localtime())

def showTime():
    return time.strftime("%H:%M:%S", time.localtime())

print(TimeTest.showTime())
t = TimeTest(2, 10, 10)
nowTime = t.showTime()
print(nowTime)

 



原文地址:https://www.cnblogs.com/wangkaiok/p/9988051.html