面向对象之类和函数的属性

一个简单的学生类

class Student(object):
    stu_school = 'hnie'
    count = 0

    def __init__(self, name, age, gender):
        Student.count += 1
        self.name = name
        self.age = age
        self.gender = gender

    def tell_stu_info(self):
        print('学生信息: 名字: %s  年龄: %s  性别: %s' % (
            self.name,
            self.age,
            self.gender
        ))

    def set_info(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

类可以访问类的属性(类属性)

1. 类的数据属性

print(Student.stu_school)

2. 类的函数属性

print(Student.set_info)

但是, 其实类中的东西是给对象用的。

类的数据属性是共享给所有的对象用的

类的数据属性是共享给所有的对象用的, 大家访问的地址都是一样的

print(id(Student.stu_school))  # 140289275056688
print(id(stu1_obj.stu_school))  # 140289275056688
print(id(stu2_obj.stu_school))  # 140289275056688

因为访问的地址都是一样的, 所以不管是通过类修改类属性还是通过对象修改类属性, 都会改变其他对象调用类属性所得到的值

Student.stu_school = 'HNIE'
print(Student.stu_school)  # 'HNIE'
print(stu1_obj.stu_school)  # 'HNIE'
print(stu2_obj.stu_school)  # 'HNIE'

stu1_obj.stu_school = 'HNIE'
print(Student.stu_school)  # 'HNIE'
print(stu1_obj.stu_school)  # 'HNIE'
print(stu2_obj.stu_school)  # 'HNIE'

通过这个现象, 我们可以通过简单的方法得到这个类一共创建了几个对象,

即定义一个类属性count, 然后在类的初始化__init__方法中实现count+1的动作即可完成

class Student(object):
    count = 0
  
    def __init__(self):
        Student.count += 1


stu1 = Student()
stu2 = Student()
stu3 = Student()

print(Student.count)  # 3
print(stu1.count)  # 3
print(stu2.count)  # 3
print(stu3.count)  # 3

类的函数属性是绑定给对象用的

类的函数属性是绑定给对象用的, 虽然所有对象指向的都是相同的功能, 但是绑定到不同的对象就是不同的绑定方法, 内存地址各不相同

类调用自己函数的时候必须按照函数的用来来操作

Student.tell_stu_info(stu1_obj)
Student.tell_stu_info(stu2_obj)

Student.set_info(stu1_obj, 'zhangjie', '20', 'male')
Student.tell_stu_info(stu1_obj)

对象调用类的方法是通过绑定方法的形式来操作的

绑定方法的特殊之处在于: 谁调用绑定方法就会将谁作为绑定方法的第一个参数自动传入

print(Student.tell_stu_info)  # <function Student.tell_stu_info at 0x7fe4326bf950>
print(stu1_obj.tell_stu_info)  # <bound method Student.tell_stu_info of <__main__.Student object at 0x7fe4326cf650>>
print(stu2_obj.tell_stu_info)  # <bound method Student.tell_stu_info of <__main__.Student object at 0x7fe4326cf710>>

 

原文地址:https://www.cnblogs.com/featherwit/p/13288899.html