类的创建

  • 创建的语法
class 类名:
  pass
#类名由多个或一个单词组成,每个单词的首字需要大写,其余小写
  • 类的组成
    1、类的属性
    2、实例方法
    3、静态方法
    4、类方法
class Student:
    native_pace='吉林' #直接写在类里的变量,称为类属性
    def __init__(self,name,age):
        self.name=name #self.name 称为实体属性,进行一个赋值操作
        self.age=age
    #实例方法
    def eat(self):
     print('学生在吃饭')
#在类之外定义的称之为函数
    #静态方法
    @staticmethod
    def method():#不能有参数
        print('这是静态方法')
    #类方法
    @classmethod
    def cm(cls):
        print('这是类方法')
def drink(self):
     print('学生在喝水')

对象的创建

  • 对象的创建形式
实例名=类名()
stu1=Student ('张三',20)
  • 方法的调用
    1、对象名.方法()
    2、类名.方法(对象名)
#创建对象
stu1=Student ('张三',20)
stu1.eat()
print(stu1.name)
print(stu1.age)
print('-----------------------')
Student.eat(stu1)

类属性、类方法、静态方法

  • 类属性:类中方法外的变量称为类属性,被该类的所有对象共享。
#类属性的创建
class 类名:
  native_pace='吉林'
#类属性的调用
print(Student.native_pace)
  • 类方法:使用@classmethod修饰的方法,使用类名直接访问方法。
#类方法的定义
 @classmethod
    def 方法名(cls):
        print('这是类方法')
#类方法的调用
Student.方法名() #在调用时cls参数是不需要传入的
  • 静态方法:使用@staticmethod修饰的方法,使用类名直接访问方法。
#静态方法的定义
    @staticmethod
    def 方法名():#不能有参数
        print('这是静态方法')
#静态方法的调用
Student.方法名()
  • 具体演示实例如下:
class Student:
    native_pace='吉林' #直接写在类里的变量,称为类属性
    def __init__(self,name,age):
        self.name=name #self.name 称为实体属性,进行一个赋值操作
        self.age=age
    #实例方法
    def eat(self):
     print('学生在吃饭')
#在类之外定义的称之为函数
    #静态方法
    @staticmethod
    def method():#不能有参数
        print('这是静态方法')
    #类方法
    @classmethod
    def cm(cls):
        print('这是类方法')
def drink(self):
     print('学生在喝水')
print('------类属性的调用------')
print(Student.native_pace)
stu1=Student('张三',20)
stu2=Student('李四',20)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace='天津'
print(stu1.native_pace)
print(stu2.native_pace)
print('------类方法的调用')
Student.cm() #在调用时cls参数是不需要传入的
Student.method()

动态绑定属性和方法

  • Python是动态语言,在创建对象之后,可以动态地绑定属性和方法。
class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def eat(self):
        print(self.name+'在吃饭')
stu1=Student('张三',20)
stu2=Student('李四',20)
Student.eat(stu1)
stu2.eat()
print('------为stu2动态绑定性别属性-------')
stu2.gender='女'
print(stu1.name,stu1.age)
print(stu2.name,stu2.age,stu2.gender)
print('------为stu2动态绑定方法-------')
def show():
    print('定义在类之外的函数,称为函数')
    #动态绑定方法
stu1.show=show
stu1.show()

python类名能做函数参数吗 python 类名.方法_类方法