面向对象的特殊方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象的特殊方法相关的知识,希望对你有一定的参考价值。
特殊方法__init__ :把各种属性绑定到self
__slots__ : 限制实例的动态属性,减少内存消耗,tuple类型
__str__: 对象的说明文字
__eq__:比较对象是否相等
classmethod 与staticmethod:classmethod 会把类本身作为第一个参数传入。
class Computer:
"""电脑"""
def __init__(self, name, mem, cpu):
self._name = name
self.mem = mem
self.cpu = cpu
def play(self, game=‘qq‘):
print(‘play games:‘,game)
pc1 = Computer(‘coop‘,‘8G‘,‘8‘) # 实例初始化,生成一个类的对象,具有类的属性和方法
pc1
<__main__.Computer at 0x1ec1ec7f0f0>
pc1.play
<bound method Computer.play of <__main__.Computer object at 0x000001EC1EC7F0F0>>
pc1.play()
play games: qq
pc1.play(‘rongyao‘)
play games: rongyao
pc1.mem
‘8G‘
pc1._name
‘coop‘
pc1.cpu
‘8‘
#############
pc1.disk = ‘ssd‘
pc1.disk
‘ssd‘
class Computer:
"""电脑"""
__slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
def __init__(self, name, mem, cpu):
self._name = name
self.mem = mem
self.cpu = cpu
def play(self, game=‘mosou‘):
print(‘play game:‘,game)
def __str__(self):
return f‘{self._name}:{self.mem}-{self.cpu}‘
pc2 = Computer(‘admin‘, ‘8G‘, ‘8‘)
pc2.mem
‘8G‘
pc2.cpu
‘8‘
pc2._name
‘admin‘
pc2.disk = ‘disk‘
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-45-35b41d1e04d2> in <module>()
----> 1 pc2.disk = ‘disk‘
AttributeError: ‘Computer‘ object has no attribute ‘disk‘
print(pc2)
admin:8G-8
pc3 = Computer(‘admin‘,‘8G‘,8)
print(pc3)
admin:8G-8
pc2 == pc3
False
############
class Computer:
"""电脑"""
__slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
def __init__(self, name, mem, cpu):
self._name = name
self.mem = mem
self.cpu = cpu
def play(self, game=‘mosou‘):
print(‘play game:‘,game)
def __str__(self):
return f‘{self._name}:{self.mem}-{self.cpu}‘
def __eq__(self, other):
return self.cpu == other.cpu
pc2 = Computer(‘admin‘,‘8G‘,8)
pc3 = Computer(‘admin‘,‘8G‘,8)
pc2 == pc3
True
###########
class Computer:
"""电脑"""
__slots__ = (‘_name‘, ‘mem‘, ‘cpu‘)
def __init__(self, name, mem, cpu):
self._name = name
self.mem = mem
self.cpu = cpu
def play(self, game=‘mosou‘):
print(‘play game:‘,game)
def __str__(self):
return f‘{self._name}:{self.mem}-{self.cpu}‘
def __eq__(self, other):
return self.cpu == other.cpu
@classmethod # 通过新的方式构造实例,区别于默认的__init__,类似其他语言重载
def new_pc(cls, info): # 第一个参数为类本身
"从字符串产生新的实例"
name, mem, cpu = info.split(‘-‘)
return cls(name, mem, cpu)
@staticmethod # 不需要生成类的实例,就可以使用的方法
def calc(a, b, oper): # 不用第一个参数
"根据操作符号+-*/计算a和b的结果"
if oper == ‘+‘:
return a + b
# 使用classmethod建立新的对象
pc111 = Computer.new_pc(‘pc111-16G-8‘)
print(pc111)
pc111:16G-8
Computer.calc(4, 3, ‘+‘)
7
Computer.calc(2, 3, "-")
以上是关于面向对象的特殊方法的主要内容,如果未能解决你的问题,请参考以下文章