【类和实例】
1、在Java中,类决定了对象的属性和方法,和Java不同,Python允许对实例变量绑定任何数据,即同类的对象可能有不同的特征。
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.score))
3、Python中如何创建对象,调用方法:
bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) bart.print_score() lisa.print_score()
【访问限制】
1、在Python中,设置私有变量的方法是self.__name = name # 双下划线!
2、之所以大费周折的写修改器方法是为了实现参数检查,避免传入无效参数。
3、尝试用Python重写顾客类:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Movie(object): def __init__(self, title, priceCode): self.__title = title self.__priceCode = priceCode def getTitle(self): return self.__title def getPriceCode(self): return self.__priceCode def setTitle(self, title): self.__title = title # 类测试 if __name__ == '__main__': movie_A = Movie('Tokyo Ghoul', 145) print(movie_A.getTitle()) movie_A.setTitle('Love Python') print(movie_A.getTitle() + ' ') print(movie_A.getPriceCode())
【继承和多态】
与Java的差异。
1、语法上。
class son(father) 等价于Java的 class son extends father
2、动态语言的鸭子类型特点。
例如:
def run(Animal): Animal.run()
传入的不一定必须是Animal的对象或是其子类对象(Java的话就必须得是!),只要是含有run方法的类对象就好了,这一特点使得继承不是那么不可替代。
【获取对象信息】
1、获取对象类型。
>>> type(123) <class 'int'> >>> type('123') <class 'str'>
2、判断是不是函数。
>>> type(f) <class 'function'>
3、判断是不是某类的实例。
>>> isinstance(123, int)
True
4、获得一个对象的所有属性和方法。
>>> dir('123') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__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', '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']
5、类似于__xxx__的方法调用方式为:
>>> class MyDog(object): ... def __len__(self): ... return 100 ... >>> dog = MyDog() >>> len(dog) 100
6、getattr()
、setattr()
以及hasattr()方法。
hasattr()
>>> hasattr(obj, 'x') # 有属性'x'吗? True
getattr()
>>> getattr(obj, 'y') # 获取属性'y' 19
可以传入一个default参数,如果属性不存在,就返回默认值:
>>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 404
以上同样对函数的成员方法使用,把变量名改成函数名就可以了(不用加括号)
setattr()
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
【实例属性和类属性】
声明方式:
>>> class Student(object): ... name = 'Student' ...
实例属性的优先级高于类属性,类属性可以通过"classname.属性名"访问,类似于Java中的静态变量。