码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象的特殊方法

时间:2018-05-18 22:52:42      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:python 对象特殊方法

特殊方法

__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, "-")

面向对象的特殊方法

标签:python 对象特殊方法

原文地址:http://blog.51cto.com/13118411/2118068

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!