python 类与对象

编程思想:1.面向对象 2.面向过程
类对象:1.类属性 2.类方法 3.实例方法 4.静态方法
实例对象: 1.类名() 创建实例对象c 2.动态绑定属性 3.动态绑定方法


print(id(Student))
print(type(Student))
print(Student)
# 5805061296
# <class 'type'>
# <class '__main__.Student'>

class Student:
    native_place = '吉林'

    def __init__(self, name, age):
        self.name = name  # 实例属性 进行赋值
        self.age = age

    # 实例方法
    def eat(self):
        print('学生在吃饭')

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

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


# 在类之外定义的称为函数,在类之内定义的称为方法
def drink():
    print('喝水')


# 创建Student类的对象
stu1 = Student('张三', 20)  # 实例对象
print(id(stu1))
print(type(stu1))
print(stu1)
print('------------------')
print(id(Student))  # 类对象
print(type(Student))
print(Student)

stu1.eat()
print(stu1.name)
print(stu1.age)

print('-------------')
Student.eat(stu1)  # stu1.eat()  一样
# 类名.方法名

# 类属性的使用方式
print(Student.native_place)

stu1 = Student('张三', 20)
stu2 = Student('李四', 30)
print(stu1.native_place)
print(stu2.native_place)
Student.native_place = '天津'
print(stu1.native_place)
print(stu2.native_place)
print('-----------类方法的使用方式--------------')
Student.cm()  # 类方法
Student.method()  # 静态方法


'''  动态绑定属性和方法'''


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

    def eat(self):
        print(self.name + '在吃饭')


stu1 = Student('李四', 30)
stu2 = Student('张三', 20)
print(id(stu1))
print(id(stu2))
print('-------为stu2动态绑定性别属性----------')
# 动态添加属性
stu2.gender = '女'
print(stu1.name, stu2.age)
print(stu2.name, stu2.age, stu2.gender)

print('-------------------')
stu1.eat()
stu2.eat()


def show():
    print('定义在类之外的方法')


stu1.show = show
stu1.show()

# stu2.show() # 并没有绑定show方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值