如何获得Python类的可能“自身属性”?

时间:2015-04-09 23:38:49

标签: python class

例如,如何在Python中定义类对象的属性?如何定义添加两个对象时会发生什么?或者将它们相乘?还是划分它们?还是打印出来?或者如果我用一些参数调用一个?

我看到__mul____add__之类的内容,但这些内容是什么以及剩下的内容是什么?

3 个答案:

答案 0 :(得分:1)

__mul____add__是您在类中调用的方法,它们分别影响您如何相乘和添加类的两个实例。这些special method names用于控制实例的运行方式。

答案 1 :(得分:1)

这称为运算符重载。

class Human(object):
    def __init__(self, name):
        self.name = name

    def __add__(self, other):
        return '{0} {1}'.format(self.name, other.name)

    def __mul__(self, other):
        return self.name * len(other.name)

    def __str__(self):
        return self.name

bob = Human('Bob')
sam = Human('Sam')

print sam + bob # calls __add__
print sam * bob # calls __mul__

print bob # calls __str__

答案 2 :(得分:0)

要知道作为对象一部分的特殊名称方法,请键入dir(object_name)

例如,要查看哪些方法是字符串的一部分:

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__'
, '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'enco
de', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind'
, 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']

请注意这些特殊方法。

而不是:

>>> "a".__add__("b")
'ab'

这样做:

>>> "a" + "b"
'ab'

以下是如何使用您自己的自定义矩阵类进行矩阵添加的示例。

class Matrix():
    def __init__(self, a):
        self.a = a
    def __add__(self, b):
        i = j = 0
        c = []
        while i < len(self.a):
            c.append([])
            while j < len(self.a[0]):
                c[i].append(self.a[i][j] + b[i][j])
                j += 1
            j = 0
            i+= 1

        return Matrix(c)

    def __getitem__(self, i):
        return self.a[i]

    def __str__(self):
        return "\n".join([str(i) for i in self.a])

a = Matrix( [[1,2,3], [4,5,6], [7,8,9]] )
b = Matrix( [[1,2,3], [4,5,6], [7,8,9]] )

print a
print "+"
print b
print "="
print a + b