Python(十):面向对象(类)

15
五月
2021

基类

  • 函数__init__()
    两个下划线,默认方法。类中必有,当创建类的实例时,python首先自动调用它
  • 形参self
    一个指向实例的引用
class Student:
    """文档字符串"""

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.professional = 'student'       # 属性默认值(区别参数默认值)

    def study(self):
        print(f"{self.name} is studying.")

    def update_age(self, age):
        self.age = age


a_student = Student("Amy", 18)
print(a_student.name)
a_student.study()

# 修改属性的值
# 方法1:直接修改
a_student.age = 20
print(a_student.age)
# 方法2:通过方法
a_student.update_age(25)
print(a_student.age)

多个类(继承、封装、多态)

  • 创建实例时,若子类有__init__(),则python不会调用父类的__init__()
    若子类没有,则调用父类的__init__()
  • 子类自动继承父类的属性和方法,self.即可
    也可通过内置函数 super() 调用父类的属性和方法
    super(). __init__()的位置很重要,如:
# 子类
    def __init__(self, name):		# 最终self.name = "Jack"
        super().__init__(name)    
        self.name = "Jack"


# 子类
    def __init__(self, name):		# 最终self.name = name
        self.name = "Jack"
        super().__init__(name)    
  • 重写与重载
    父类的函数func()
    子类的函数func()
    重写:子类的func()与父类的函数名和参数均相同,子类只有自己的func(),父类的被覆盖
    重载:子类的func()与父类的函数名相同,参数不同,子类有父类的func()和自己的func()

  • 单继承:super()
    多继承:子类的属性是某个类的实例

class Student:
    """文档字符串"""

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.professional = 'student'       # 属性默认值(区别参数默认值)

    def study(self):
        print(f"{self.name} is studying.")

    def update_age(self, age):
        self.age = age


class Hobby:
    """这是一个爱好"""

    def __init__(self, hobby_name="reading"):
        self.hobby_name = hobby_name

    def print_hobby(self):
        print(self.hobby_name)


class Girl(Student):
    """文档字符串"""

    def __init__(self, name, age, hobby_name):
        super().__init__(name, age)     # 显示调用父类的__init__()
        self.sex = 'female'
        self.hobby = Hobby(hobby_name)  # 属性为某个类的实例

    # 重写父类的方法
    def study(self):
        print(f"A girl {self.name} is studying in.")


a_girl = Girl("Amy", 18, "dancing")
a_girl.study()
a_girl.update_age(20)       # 调用父类的方法
print(a_girl.age)
a_girl.hobby.print_hobby()

str 与 repr

都是将类的实例转换为字符串

当 str 和 repr 均有时:

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

	def __str__(self):
		return '(str, {}, {})'.format(self.name, self.age)
		# return str(('repr', self.name, self.age))
	
	def __repr__(self):
		return repr(('repr', self.name, self.age))
		# return '(repr, {}, {})'.format(self.name, self.age)

stu = Student('a', 20)
print(stu)			# (str, a, 20)
print(str(stu))		# (str, a, 20)
print('{}'.format(stu))		# (str, a, 20)

print([stu])			# [('repr', 'a', 20)]
print(repr(stu))		# ('repr', 'a', 20)

li = [
	 Student('a', 20),
	 Student('b', 40)
]
print(li)		# [('repr', 'a', 20), ('repr', 'b', 40)]

当只有 repr 时:

class Student():
	def __init__(self, name, age):
		self.name = name
		self.age = age
		
	def __repr__(self):
		return repr(('repr', self.name, self.age))

stu = Student('a', 20)
print(stu)			# ('repr', 'a', 20)
print(str(stu))		# ('repr', 'a', 20)
print('{}'.format(stu))		# ('repr', 'a', 20)

print([stu])			# [('repr', 'a', 20)]
print(repr(stu))		# ('repr', 'a', 20)

li = [
	 Student('a', 20),
	 Student('b', 40)
]
print(li)		# [('repr', 'a', 20), ('repr', 'b', 40)]

当只有 str 时:

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

	def __str__(self):
		return '(str, {}, {})'.format(self.name, self.age)

stu = Student('a', 20)
print(stu)			# (str, a, 20)
print(str(stu))		# (str, a, 20)
print('{}'.format(stu))		# (str, a, 20)

print([stu])			# [<__main__.Student object at 0x0000021B652F1B20>]
print(repr(stu))		# <__main__.Student object at 0x0000021B652F1B20>

li = [
	 Student('a', 20),
	 Student('b', 40)
]
print(li)		# [<__main__.Student object at 0x0000021B652E4970>, <__main__.Student object at 0x0000021B652E40A0>]
调用时机strrepr
print√(优先)
字符串、tuple√(优先)
列表×
repr×

https://baijiahao.baidu.com/s?id=1596817611604972751&wfr=spider&for=pc

TAG

网友评论

共有访客发表了评论
请登录后再发布评论,和谐社会,请文明发言,谢谢合作! 立即登录 注册会员