一、类对象、实例方法、类方法、静态方法、函数

  • 类作用域内定义的函数的称为方法,作用域外定义的称为函数。

  • 静态方法通过@staticmethod标识

  • 类方法通过@classmethod标识,方法含参数cls

  • 类对象:python解释器加载类时所创建的对象

  • 实例对象:通过类创建的对象

# 类对象
class Student:

    age = 18
    name = ""
    # 类属性:所有实例共享
    native_location="北京"

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

    # 实例方法
    def study(self):
        print("我正在学习")

    # 静态方法
    @staticmethod
    def methodStatic():
        print("静态方法")


    # 类方法,参数为cls,即class缩写
    @classmethod
    def methodClass(cls):
        print("类方法")

# 函数
def eat():
    print("我正在吃")

二、方法调用

  • 类调用实例方法:需要传递实例对象作为参数

  • 类方法的调用:通过类对象调用

  • 静态方式使用:通过类对象调用

  • 类属性调用:实例对象和类对象均可访问,即类属性:所有实例共享

import student_py as sp

# 实例对象
student = sp.Student("张三", 18)
student.study()

print(id(student))
print(type(student))
print(student)

# 类调用实例方法,需要传递实例对象作为参数
print("类调用实例方式,需要传递实例对象作为参数")
sp.Student.study(student)

# 类方法使用
sp.Student.methodClass()

# 静态方式使用
sp.Student.methodStatic()

# 类属性调用
sp.Student.native_location="上海"
print(sp.Student.native_location)

# 类属性也可以通过实例对象访问
print(student.native_location)

student.native_location="广州"
print(sp.Student.native_location)



打印结果如下:

我正在学习
1645329145904
<class 'student_py.Student'>
<student_py.Student object at 0x0000017F15426030>
类调用实例方式,需要传递实例对象作为参数
我正在学习
类方法
静态方法
上海
上海
上海

三、类对象的原理

在 Python 中,“一切皆对象”。当你执行 class Dog: ... 这行代码时,Python 解释器会做两件事:

  1. 执行类体中的代码。

  2. 在内存中创建一个名为 Dog 的类对象。

这个类对象本身也拥有属性和方法,例如 __name__ (类名)、__dict__ (包含类所有属性和方法的字典) 等。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐