'''

封装:

把乱七八糟的数据扔进列表里面,这是数据层面的封装

把常用的代码段打包成一个函数,这是语句层面的封装

把数据和代码打包成一个对象,这也是封装

对象的特征称为“属性”,对象的行为称为“方法”,即: 对象 = 属性 + 方法

从代码层面看,“属性”就是变量,“方法”就是函数,将定义的这些称为类(class)

对象叫做这个类的一个实例(instance),也叫实例对象(instance object)

'''

# 类名约定用大写字母开头,含 class 表明定义一个类

class Gm():

str = "这是一个类属性(类变量)"

# 函数名用小写字母开头,含 def 表明定义一个函数

def instancefunc(self):

print("这是一个实例方法")

print(self)

@classmethod # 该装饰器用来标识为类方法,可以访问类属性

def classfunc(cls): # 第一个参数必须是类对象(cls.)

print("这是一个类方法")

print(cls)

@staticmethod # 该装饰器用来标识为静态方法,不可以访问类属性

def staticfunc(): # 形参没有 self 或 cls

print("这是一个静态方法")

# Gm1(继承类)是子类,Gm(被继承的类)是基类、父类或超类。

# 一个子类可以继承分类的任何属性和方法。

# 若子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性

class Gm1(Gm):

pass

# 调用

test = Gm() # 初始化一个Gm的对象(创建一个Gm对象),即test是Gm的实例对象

print(test)

print("**************************************")

test.instancefunc() # 对象调用实例方法

test.classfunc() # 对象调用类方法

test.staticfunc() # 对象调用静态方法

print("**************************************")

print(test.str)

print("**************************************")

Gm.staticfunc() # 类调用静态方法

Gm.classfunc() # 类调用类方法

Gm.instancefunc(test) # 类调用实例方法,需要带参数

1258919-20200604145200899-1690583359.png

实例方法:

class Gm():

str = "这是一个类属性(类变量)"

def __init__(self, st):

self.st = st

def instancefunc(self):

print("这是一个实例方法")

print(Gm.str)

print(self.st)

print(self.str)

print(self)

if __name__ == '__main__':

test = Gm("abc")

print(test)

print(test.str)

print(test.st)

test.instancefunc()

1258919-20200604151129251-1953272538.png

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐