廖雪峰python3教程学习随笔

(未完)
1.创建实例的时候,需要定义一个特殊的__init__方法,而且它的第一个参数永远是self,表示创建的实例本身。因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。

>>> class Student(object):
...     def __init__(self,name,score):
...             self.name=name
...             self.score=score

定义了__init__后,创建实例的时候就不能传入空参,除了self外,其它参数必须与__init__匹配


2.在python中,变量如果以两个下划线开头,那这个变量就变成了一个私有变量 如:
class Student(object):
    def __init__(self,name,score):
        self.__name=name
        self.__score=score
    def print_score(self):
        print('%s:%s'%(self.__name,self.__name))

3.在外部直接设置对象的属性与用setter方法设置对象属性相比,缺点在于前者不能设置一些语句对传入的值进行判断,不能防止被传入恶意的值。
4.以双划线开头+结尾的变量是特殊变量,比如__xxx__,是可以直接访问的。
5.判断对象的类型:使用type()函数:
>>> type(123)
<class 'int'>
>>>

6.可以使用dir()获取一个对象的所有属性和方法:
>>> dir('123')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

类似__xxx__的属性和方法在python中都是有特殊用途的,比如__len__方法返回长度。在python中,如果调用len()函数试图获取一个对象的长度,在这个函数的内部,它会自动调用该对象的__len__()方法。对于我们自己写的类,如果也想调用len(object),就得自己写一个__len__()方法。































猜你喜欢

转载自blog.csdn.net/yuanren201/article/details/88719717
今日推荐