Python面向对象编程——学习笔记

来源:互联网 发布:淘宝促销代码 编辑:程序博客网 时间:2024/05/09 19:09
1.  非公开的(private)的函数或变量,不应该被直接引用,比如_abc__abc等; 正常的函数和变量名是公开的(public),可以被直接引用,比如:abcx123PI等;__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author____name__就是特殊变量
有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
2.   第三方模块引入声明(PIL:Pillow)
from PIL import Image
3.   引入自己写的模块
import modulename
4.   继承父类的规则与Java类似
  • 类内部有一个__init__(self)方法,类似于Java的构造函数
  • 类内部的方法必须至少有一个self参数,在实例调用该方法是,不需要传入self参数
  • 类的属性定义都是在__init__(self)中,这点与Java有较大差异。在该方法中允许将属性写入参数列表,要求实例化的时候必须传入该参数,也可以不写入参数列表,在方法中设置默认值。
  • 在方法内部self的使用类似Java的this
5.
type([1,2,3]) # list判断数据、函数类型   isinstance(dog,animal) # true 判断实例类型   dir(dog)  #返回一个对象的所有属性和方法信息
6.   
len('hello')=='hello'.__len__()<span style="font-family:Consolas;">  # </span>__len__()是str对象的一个方法
7.  
>>> dir('ABC')['__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']
这些都是方法。
__xxx__使用方法是xxx('ABC')
xxx使用方法都是'ABC'.xxx()
8、
getattr(obj,'x') #获取obj中属性x的值setattr(obj,'y',19)#设置一个obj的属性y,并将其值赋为19hasattr(obj,'y')#obj有y这个属性吗?</span>
9、类属性
class Student(object):    name = 'Victoria'# 类的实例以覆盖的方式修改类的属性值class Car:    _color = ""    def description(self,name):        self.name=name        name2=name #这个name2是类和实例都是无法访问的,当然该类的其他方法更加无法访问,只能在该方法内部使用,算是局部变量        description_string = "This is a %s car %s." % (self._color ,self.name)        return description_stringcar1 = Car()car1._color = "blue"  #实例可以重写类属性print(car1.description('11')) #This is a blue car 11.print(hasattr(Car,'name')) #Falseprint(hasattr(Car,'_color')) #Trueprint(hasattr(car1,'name')) #Trueprint(hasattr(car1,'_color')) #Trueprint(Car.name) #Error类无法直接访问实例属性print(car1.name) #11
类属性:写在类内部,方法外部的属性
实例属性:写在类的方法内部,前面有self.的属性

self指的是类实例对象本身(注意:不是类本身)。


声明:学习廖雪峰的Python教程——面向对象编程章节后的学习笔记,感谢Micheal Liao.



0 0
原创粉丝点击