# **************************************************************************
# Python学习
# **************************************************************************
# ** 所属主题:
# ** 所属分层: 03 属性的查找与绑定的方法
# ** 功能描述: 03 属性的查找与绑定的方法
# ** 创 建 者: 陈红伟
# ** 创建日期: 2021/6/18 12:07 上午
# **************************************************************************
# ** 修改日期 修改人 修改内容
# ** 2021/6/18 陈红伟 新增学习内容代码
# ** 2021/6/20 陈红伟 新增单继承背景下的属性查找
# **************************************************************************
"""
一、属性查找
"""
class Student:
school_name = 'chw'
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def select_school_name(self):
return self.school_name
def select_name(self):
return self.name
# 注意⚠️:因为name是该类的实例才特有的属性,所以在类Student中没有该属性的,故不能被直接调用,
# 会报错:AttributeError: type object 'Student' has no attribute 'name'
def set_name(self, name):
self.name = name
stu1 = Student('张三', 18, '男')
stu2 = Student('里斯', 18, '男')
stu3 = Student('王武', 18, '男')
# 属性的查找
print(Student.school_name) # chw
print(stu1.school_name) # chw
# print(Student.name) # AttributeError: type object 'Student' has no attribute 'name' 因为是对象特有的
print(stu1.name) # 张三
print(stu2.name) # 里斯
print(stu3.name) # 王武
# 修改类属性
print(Student.school_name) # chw
print(stu1.school_name) # chw
stu1.school_name = '789'
print(Student.school_name) # chw
print(stu1.school_name) # 789
Student.school_name = 'new_name'
print(Student.school_name) # new_name
print(stu1.school_name) # 789
# 访问类中方法
# print(Student.select_name(Student)) # AttributeError: type object 'Student' has no attribute 'name'
print(Student.select_school_name(Student)) # new_name
print(stu1.select_name()) # 张三
print(stu1.name)
print(stu2.name)
print(stu3.name)
# 张三
# 里斯
# 王武
Student.set_name(stu1, 'ccc') # 这种调用方式很不直观,所以引用绑定的概念
print(stu1.name)
print(stu2.name)
print(stu3.name)
# ccc
# 里斯
# 王武
# 20210620 17:45:00
"""
单继承背景下的属性查找:
"""
class Foo(object):
def f1(self):
print('Foo.f1')
def f2(self):
print('Foo f2')
self.f1()
class Bar(Foo):
def f1(self):
print("Bar f1")
b = Bar()
b.f2()
# Foo f2
# Bar f1
# 基于上面例子,那如果想要调用当前类的f1() ==> (输出 Foo f1),怎样实现?
# 答案:
# 1、强行使用Foo.f1()
# 2、利用之前学过的隐藏(稀有)知识点。变成self__f1()
class Foo(object):
def __f1(self): # 加上__后,类在定义阶段名,该方法已经发生了变形,变成类 _Foo__f1
print('Foo.f1')
def f2(self):
print('Foo f2')
# self.f1()
# Foo.f1() 答案1
self.__f1() # self._Foo__f1 答案2
class Bar(Foo):
def __f1(self): # _Bar__f1
print("Bar f1")
obj = Bar()
# obj.f1() # AttributeError: 'Bar' object has no attribute 'f1'
obj.f2()
# Foo f2
# Foo.f1
"""
二、绑定方法:
绑定方法的特殊之处在于:谁来调用绑定方法就会将谁当作第一个参数自动传入
(谁调用我,我的对象【self】就是谁)
"""
# 未利用绑定概念:
Student.set_name(stu1, 'ccc')
print(stu1.name) # ccc
# 利用绑定的概念:
stu1.set_name('bbb')
print(stu1.name) # bbb
Python基础51:属性的查找与绑定的方法
最新推荐文章于 2024-05-17 16:57:41 发布