Python学习(3)

来源:互联网 发布:上海网络电视台回看 编辑:程序博客网 时间:2024/06/11 21:48

本系列内容来源于 廖雪峰的Python教程 点击查看原文

面向对象

访问限制class Message:    def __init__(self, id, content):        self._id = id;        self._content = content;变量名以 __开头  如__id  。都是私有变量,外部一般不能访问

继承,多态请自行查看

点这

获取对象信息

>>> type(123)<class 'int'>>>> type('str')<class 'str'>>>> type(None)<type(None) 'NoneType'>>>> type(123)==type(456)True>>> type(123)==intTrue>>> type('abc')==type('123')True>>> type('abc')==strTrue>>> type('abc')==type(123)False对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数。

列出和操作对象的状态

class MyObject(object):    def __init__(self):        self.x = 9    def power(self):        return self.x * self.xobj = MyObject()列出:>>> dir(obj)['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'power', 'x']测试>>> hasattr(obj, 'x') # 有属性'x'吗?True>>> obj.x9>>> hasattr(obj, 'y') # 有属性'y'吗?False>>> setattr(obj, 'y', 19) # 设置一个属性'y'>>> hasattr(obj, 'y') # 有属性'y'吗?True>>> getattr(obj, 'y') # 获取属性'y'19>>> obj.y # 获取属性'y'19

实例属性和类属性
* 1 给一个实例绑定一个实例变量

class Student(object):    def __init__(self,name):        self.name = names = Student('Alice')s.age = 10   #动态给一个实例绑定变量
  • 2 类属性
class Student(object):    name = "Student">>> s = Student() # 创建实例s>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性Student>>> print(Student.name) # 打印类的name属性Student>>> s.name = 'Michael' # 给实例绑定name属性>>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性Michael>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问Student>>> del s.name # 如果删除实例的name属性>>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了Student

使用slots:给类绑定属性和方法

一般绑定属性

class Studeng():    pass>> s = Studeng()>> s.name = "haha" # 动态给实例绑定一个属性>> print(s.name)

一般绑定方法

>>> def set_name(self,name):  #定义一个方法    self.name = name;>>> s = Student()>>> s.set_name = MethodType(set_name,s) #给实例绑定一个方法>>> s.set_name("haha")>>> s.name'haha'#给类绑定方法>>> def set_score(self, score):        self.score = score>>> Student.set_score = set_score

使用__slots__绑定

class User(object):    __slots__ = ('name','age') #用tuple定义允许绑定的属性名称>>> s = User()>>> s.name = 'haha'>>> s.age = '22'>>> s.score = 100Traceback (most recent call last):  File "<pyshell#22>", line 1, in <module>    s.score = 100AttributeError: 'User' object has no attribute 'score'注:__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的,除非在子类中也定义__slots__

使用@property

更简单的getter setter ,@property装饰器就是负责把一个方法变成属性class Student(object):    @property    def score(self):        return self._score    @score.setter    def score(self, value):        if not isinstance(value, int):            raise ValueError('score must be an integer!')        if value < 0 or value > 100:            raise ValueError('score must between 0 ~ 100!')        self._score = value     @property    def age(self):        return 2015 - self._birth    ---------------------------------------------------    @property 就是把一个方法转变为一个属性,属于getter方法。    @ .setter 也是把一个方法转变为一个属性,属于setter方法    只有@property 是一个只读属性。代码里面的age方法
原创粉丝点击