05_python基础_对象和类

class Student:
    place = 'BJ' # 类属性:类中方法外的变量称为类属性,被该类所有的对象共享,使用类名调用

    # 初始化方法
    def __init__(self, name, age):  # self.name和self.age都是实例属性,将局部变量的name值赋给实例属性,self就是创建的stu对象自身,所以stu对象才能调用实例属性和方法
        self.name = name
        self.__age = age  #age不希望在类外部使用,加"__",但是可以在内部使用

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

    # 类方法 不允许写self,写cls:被@classmethod修饰的方法,使用类名直接访问的方法Student.cm()
    @classmethod
    def cm(cls):
        print('类方法')

    # 静态方法 不允许写self,没有参数:被@staticmethod修饰的方法,使用类名直接访问的方法Student.sm()
    @staticmethod
    def sm():
        print('静态方法')

stu1 = Student('wjx',25)
stu1.gender = 'top'  # 动态绑定属性,因为初始化方法中没有该实例属性gender
print(stu1.name, stu1.gender)

def show():
    print('stu1的动态绑定方法')
stu1.show = show # 动态绑定方法,独属于stu1的方法,该show()方法定义在类之外
stu1.show()

#print(stu1.__age)   # AttributeError: 'Student' object has no attribute '__age'
print(dir(stu1))
print(stu1._Student__age)  # 在类外部可以通过_Student__age访问
posted @   漂洋过海去见你  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示