类方法、绑定的类、静态方法
# !/usr/bin/python3# -*- coding: utf-8 -*-
# @Time : 2023/2/23 20:41
# @Author : xiongming
# @File : lei_Func.py
# @Desc : 类方法、绑定的类、静态方法
class A:
def funA(self):
print(self)
@classmethod
def funB(cls):
print(cls)
a = A()
# 绑定的对象 object<__main__.A object at 0x7fb4e005eeb0>
print(a.funA())
# 类 <class '__main__.A'>
print(a.funB())
class C:
count = 0
def __init__(self):
C.count += 1
@classmethod
def get_count(cls):
print(f"该类一共实例化了{cls.count} 个对象")
c1 = C()
c2 = C()
c3 = C()
c3.get_count()
c3.count = 1
print(c3.count)
print(c3.get_count())
# 静态方法 不需要绑定
class B:
@staticmethod
def funC():
print("I love FishC")
b = B()
b.funC()
B.funC()
# 涉及继承问题
class E:
count = 0
@classmethod
def add(cls):
cls.count +=1
def __init__(self):
self.add()
@classmethod
def get_count(cls):
print(f"该类一共实例化了{cls.count} 个对象")
class W(E):
count = 0
class F(E):
count = 0
e1 = E()
w1, w2 = W(), W()
f1, f2, f3 = F(), F(), F()
e1.get_count()
w1.get_count()
f1.get_count()
页:
[1]