马士兵Python学习笔记_P110_109.类属性_类方法_静态方法的使用方式

马士兵Python学习笔记_P110_109.类属性_类方法_静态方法的使用方式

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

在这里插入图片描述

二、代码示例

print("------------------------------- 类的组成 ------------------------------------")
class Student:
    native_place = "吉林"     # 直接写在类里面的变量,称为 类属性

    def __init__(self, name, age):
        self.name = name    # self.name 称为 实例属性,进行了一个赋值的操作,将局部变量 name 的值赋给 实例属性
        self.age = age

    # 在类之内定义的称为:实例方法;在类之外定义的称为 函数。
    def eat(self):   # 括号中要写 self,或者用其他名字
        print("学生在吃饭……")

    # 静态方法
    @staticmethod
    def method():   # 括号中不允许写 self
        print("我使用了 @staticmethod 进行修饰,所以我是 静态方法")

    # 类方法
    @classmethod
    def cm(cls):   # 括号中要写 cls
        print("我使用了 @classmethod 进行修饰,所以我是 类方法")


# 在类之外定义的称为 函数;在类之内定义的称为:实例方法。
def drink():
    print("喝水")

print("------------------------------- 类属性 的使用方式 ------------------------------------")
print(Student.native_place, type(Student.native_place), id(Student.native_place))
stu1 = Student("张三", 20)
stu2 = Student("李四", 30)
print(stu1.native_place, type(stu1.native_place), id(stu1.native_place))
print(stu2.native_place, type(stu2.native_place), id(stu2.native_place))
Student.native_place = "天津"
print(Student.native_place, type(Student.native_place), id(Student.native_place))
print(stu1.native_place, type(stu1.native_place), id(stu1.native_place))
print(stu2.native_place, type(stu2.native_place), id(stu2.native_place))

print("------------------------------- 类方法 的使用方式 ------------------------------------")
Student.cm()

print("------------------------------- 静态方法 的使用方式 ------------------------------------")
Student.method()

运行结果:

D:\Environment\Python\Python311\python.exe D:\Environment\PythonWorks\learnpython\马士兵Python\第12章_找对象不积极思想有问题\P110_109.类属性_类方法_静态方法的使用方式.py 
------------------------------- 类的组成 ------------------------------------
------------------------------- 类属性 的使用方式 ------------------------------------
吉林 <class 'str'> 2004827926000
吉林 <class 'str'> 2004827926000
吉林 <class 'str'> 2004827926000
天津 <class 'str'> 2004827930128
天津 <class 'str'> 2004827930128
天津 <class 'str'> 2004827930128
------------------------------- 类方法 的使用方式 ------------------------------------
我使用了 @classmethod 进行修饰,所以我是 类方法
------------------------------- 静态方法 的使用方式 ------------------------------------
我使用了 @staticmethod 进行修饰,所以我是 静态方法

Process finished with exit code 0

B站视频链接:https://www.bilibili.com/video/BV1wD4y1o7AS?p=110

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值