关于python中的类,很详细

类的组成

·类属性

·实例方法

·静态方法

·类方法

创建类的语法(基本模板)

class Student:    #Student为类的名字,
    native_place='吉林'   #类属性
    def __init__(self,name,age):    #name,age为实例属性,直接写在类里的变量,称为类属性
        self.name=name  #self.name为实例属性,进行了一个赋值操作,将局部变量name赋值给实例属性
        self.age=age

    #实例方法
    def info(self):
        print('我的名字叫:',self.name,'年龄是:',self.age)

    #类方法
    @classmethod
    def sm(cls):
        print('类方法')

    #静态方法
    @staticmethod
    def sm():
        print('静态方法')

对象的创建

·语法:

    实例名=类名()

·意义:有了实例,就可以调用类的内容

·创建Student类的实例对象:
stu1=Student('Jack',20)
print(stu1.name)
print(stu1.age)
stu1.info()

在这里插入图片描述

方法的调用

··方法一:stu1.eat()   #对象名.方法名

··方法二:Student.eat(stu1)    #类名.方法名(类的对象)

类属性,类方法,静态方法

·类属性:类中方法外的变量称为类属性,被该类的所有对象所共享 

·类方法:使用@classmethod修饰的方法, 使用类名直接访问的方法 

·静态方法:使用@staticmethod修饰的主法, 使用类名直接访问的方法

·使用方法:

print('---------类属性的使用方法-----------')
print(Student.native_place)
print('---------类方法的使用方式-----------')
Student.cm()
print('---------静态方法的使用方式-----------')
Student.sm()

动态绑定属性和方法

·一个Student类可以创建N多个Student类的实例对象,每个实例对象的属性值不同。

·Python是一门动态语言,在创建对象之后,可以动态的绑定属性和方法

·动态绑定属性:
stu1.gender='女'    #此属性只允许stu1使用,stu2不可使
·动态的绑定方法:
#为stu1单独绑定show()方法
def shou():
    pass
stu1.shou=shou
stu1.shou()

知识点总结

在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_51756104/article/details/121278538