Python(三十)python中的类class

100 阅读4分钟

Python是一门面向对象语言。

Class类是面向对象中非常重要的一个元素

什么是类呢?

Class类是一个功能的合集。

一:类的创建

1 :类的构造函数

# 定义类
class tests:
    '测试创建类' # 类文档字符串
    projectName=''
    def __init__(self,name):
        print("初始化类调用了构造函数")
        self.projectName = name
        print("构造函数接收到了参数:",self.projectName)

T = tests('时间里的')

输出:

初始化类调用了构造函数
构造函数接收到了参数: 时间里的

 

第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法

self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

 

构造函数这个东西好像每个语言(目前我遇到的)基本上都差不多。

 

上边的类型我定义了一个类的成员变量projectName,这个是公共(public)权限的,关于这部分,后边的类的继承中会讲到。

 

2 :self参数

类的方法都有一个固定的参数self(不一定非的是self,换成其他名字也可以)

类的方法和函数的区别就是这个,函数可以没有参数,类的方法必须有一个格外的参数

self 代表类的实例,而非类

class Test:
    def prt(self):
        print(self)
        print(self.__class__)


t = Test()
t.prt()

输出:

<classObj.Test object at 0x0000027065349348>
<class 'classObj.Test'>

从上边的代码我们可以看出:

Self指向类的对象

Self.__class__指向类

 

3 :一个完整的类(构造函数,方法,属性)

# 定义类
class Student:
    """
    测试创建类
    """
    # name
    name = ''
    # age
    age = ''
    # 构造函数
    def __init__(self, name, age):
        print("初始化类调用了构造函数")
        self.name = name
        self.age = age
        print("构造函数接收到了参数:", self.name)
    # 获取 学生信息
    def getStudentInfo(self):
        li = {'name': self.name, 'age': self.age}
        return li


T = Student('时间里的'18)
li = T.getStudentInfo()
print('学生姓名:', li['name'])
print('学生年龄:', li['age'])

类的getStudentinfo方法返回的是一个字典

我们可以通过key来访问字典中的值

 

二:类的内置属性

dict : 类的属性(包含一个字典,由类的数据属性组成)

doc :类的文档字符串

name: 类名

module: 类定义所在的模块(类的全名是'main.className',如果类位于一个导入模块mymod中,那么className.module 等于 mymod)

bases : 类的所有父类构成元素(包含了一个由所有父类组成的元组)

class Employee:
    """
    员工类
    """
    name = ''
    duty = ''
    count = 0

    def __init__(self, name, duty):
        self.name = name
        self.duty = duty

    def displayCount(self):
        self.count += 1
        print("类对象的属性: %d" % self.count)
        print("类的属性: %d" % Employee.count)
    
    def displayEmployee(self):
        print("Name : ", self.name, ", Salary: ", self.duty)


E = Employee('camellia''收银')
# 获取类文档
print("class的__doc__函数:", Employee.__doc__)
# 获取类名称
print("class的__name__函数:", Employee.__name__)
# 获取类文件
print("class的__module__函数:", Employee.__module__)
# 类的所有父类构成元素
print("class的__bases__函数:", Employee.__bases__)
# 类的属性
print("class的__dict__函数:", Employee.__dict__)
# 调用方法
E.displayCount()

输出:

class的__doc__函数:
    员工类
   
class的__name__函数: Employee
class的__module__函数: classObj
class的__bases__函数: (<class 'object'>,)
class的__dict__函数: {'__module__''classObj''__doc__''\n    员工类\n    ''name''''duty''''count'0'__init__': <function Employee.__init__ at 0x000002129D945318>, 'displayCount': <function Employee.displayCount at 0x000002129D945678>, 'displayEmployee': <function Employee.displayEmployee at 0x000002129D945828>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>}
类对象的属性: 1
类的属性: 0

 

三:类对象的销毁

当我们实例化一个类,在这个类不被使用的时候,我们需要使用析构函数__del__来销毁他。

class Employee:
    """
    员工类
    """
    name = ''
    duty = ''
    count = 0

    def __init__(self, name, duty):
        self.name = name
        self.duty = duty

    def displayCount(self):
        self.count += 1
        print("类对象的属性: %d" % self.count)
        print("类的属性: %d" % Employee.count)

    def displayEmployee(self):
        print("Name : ", self.name, ", Salary: ", self.duty)

    def __del__(self):
        print('进入析构函数')

E1 = Employee('camellia''程序员')
# 打印变量id
print(id(E1))
# 销毁对象
del E1
# 再次打印对象id(因为对象在上一步中已销毁,因此,这里程序会报错)
try:
    print(id(E1))
except:
    print("变量已销毁!")

输出:

2149086649160
进入析构函数
变量已销毁!

 

具体相关的解释在代码中有注释,将上边的代码复制到你的pycharm中尝试一下就好。

 

四:类的静态方法以及类方法

Python的类中为我们提供了两个特殊的方法,类方法:classmethod 静态方法:staticmethod

这两种方法都不需要实例化类就可以被类本身调用

 

1 :静态方法 staticmethod

语法:

staticmethod(function)

示例:

class Test:
    name = "时间里的"
    def __int__(self):
        pass
    @staticmethod
    def staticss():
        print("调用类的静态方法")
        print("调用类的属性:", Test.name)


# 类的调用
Test.staticss()
# 类的对象调用
T = Test()
T.staticss()

输出:

调用类的静态方法
调用类的属性: 时间里的
调用类的静态方法
调用类的属性: 时间里的

 

静态方法staticmethod可以通过类调用,也可以通过类的对象调用,都可以。

 

2 :类方法 classmethod

类方法必须有一个参数 cls 这个是固定的

class Test:
    name = "时间里的"
    def __int__(self):
        pass
    @classmethod
    def classMe(cls):
        print("调用类的类方法")
        print("调用类的属性:", cls.name)


# 类的调用
Test.classMe()
# 类的对象调用
T = Test()
T.classMe()

输出:

调用类的类方法
调用类的属性: 时间里的
调用类的类方法
调用类的属性: 时间里的

 

以上大概就是python类的基础使用

 

有好的建议,请在下方输入你的评论。