Python learning-Object-oriented learning

Source: Internet
Author: User

Object-oriented 1. Construction method and destructor method
class People(object):    # 构造方法:__init__(),在实例化对象时自动执行的方法    def __init__(self, name, age):        self.name = name        self.age = age        print("创建对象成功.......")    #  析构函数:__del__(), 当你删除对象时,自动调用的方法    #  删除对象:del 对象名    def __del__(self):        print("删除对象成功.......")
1. Constructors: init()

Used to initialize the content part state of the class, which is the function that executes when the class is instantiated. Then we can put the attributes that we want to initialize first into this function.
Init () method is optional and if not provided, Python gives the default init method. Get and set methods for general data acquisition need to be defined

2. Destructors: del()

When you use Del to delete an object, it calls his own destructor, and when the object is called in a scope, the destructor is also called once when it is out of scope, which can be used to free up memory space.
del () is also optional, and if not provided, Python provides default destructors in the background if you want to explicitly call a destructor, you can use the DEL keyword, in the way: Del object name

2. str and repr methods for objects

Both repr and STR are used for display, STR is user-oriented, and repr is for programmers.
If you want to display objects using print (object), then you need to refactor Str. To print a class object directly, you need to refactor repr, and of course it can use print (object) to display the object. The difference is that when you print a class, then print first calls the defined Str method in the class, not the Repr method, and calls the Repr method without the Str method.

#定义类>>> class Test():    def __init__(self):        self.ppx = "hello,python."#实例化类,然后想直接获取类的一些信息>>> t = Test()>>> t<__main__.Test object at 0x0000000002F3EF28>>>> print(t)<__main__.Test object at 0x0000000002F3EF28>

When there is no str or repr method, the above-printed class object shows the memory address of the object
Let's refactor the repr of the class and strto see the difference between the two.

>>> class TestRepr(Test):    def __repr__(self):        return "Show:%s"%self.ppx>>> t1 = TestRepr()>>> t1Show:hello,python.>>> print(t1)Show:hello,python.

As you can see, after refactoring the repr method, the information that is printed either directly from the output object or through print is displayed in the format defined in our repr method

>>> class TestStr(Test):    def __str__(self):        return "Show:  %s"%self.ppx>>> t2 = TestStr()>>> t2<__main__.TestStr object at 0x00000000031C33C8>>>> print(t2)Show:  hello,python.

The direct output of the object TS is not output in the format defined in our str method, and information that is output with print (object) is displayed as such.

3.formate method 1. Populating a string with a location
print("hello %s" % (‘world‘))print("hello {0}".format((1, 2, 3, 4)))print("hello {0} {1} {0} {1}".format((1, 2, 3, 4), "python"))print("hello {0:.3f}".format(1.8989))运行输出:hello worldhello (1, 2, 3, 4)hello (1, 2, 3, 4) python (1, 2, 3, 4) python
2. Fill with key
print("max:{max} min:{min}".format(min=10, max=100))运行输出:max:100 min:10
3. Fill with subscript/index
point = (3,4)print("x:{0[0]}, y:{0[1]}".format(point))输出:x:3, y:4
4. Through the dictionary key
d = {‘max‘:100.7849758475976, ‘min‘:10.4756895769857985}print("max:{max:.2f} min:{min:.3f}".format(**d))运行输出:max:100.78 min:10.476
5. Working with OOP objects
class Book(object):    def __init__(self, name, author, state, bookIndex):        self.name = name        self.author = author        # 0:借出 1:未借出        self.state = state        self.bookIndex = bookIndex    # 打印对象时自动调用;str(对象)    def __str__(self):        return "书名:{0.name} 状态:{0.state}".format(self)        # return "书名:{d.name} 状态:{d.state}".format(d=self)b = Book("java", ‘aa‘, 1, ‘Index‘)print(b)运行输出:书名:java 状态:1
6. The format Magic method in the object
# 定义一个存储年月日输出格式的字典formats = {    ‘ymd‘:"{d.year}-{d.month}-{d.day}",    ‘mdy‘:"{d.month}/{d.day}/{d.year}",}class Date(object):    def __init__(self, year, month, day):        self.year = year        self.month = month        self.day = day    # format方法: format(对象名)时自动调用    def __format__(self, format_spec=None):        if not format_spec:            format_spec = ‘ymd‘        fmt = formats[format_spec] # "{d.year}-{d.month}-{d.day}".format(d=d)        return  fmt.format(d=self)d = Date(2019, 8, 25)print(format(d))    #不传入参数print(format(d, ‘mdy‘))     #传入参数运行输出:2019-8-258/25/2019
4. About @property

Accustomed to the rigor of high-level language, and always want to access control of properties, relatively safe, such as directly in the init definition of common properties, from the encapsulation, it is a bad wording. The Br/> property access control mechanism, one of which is the @propery keyword. With this keyword, its get, set function, must be consistent with the property name.
< p="">

From Requests.compat import Basestringclass Animal (object): Def __init__ (self, Name, age): Self._name = Name     Self._age = Age Self._color = ' Black ' # turns the normal method into a property method @property def name: return self._name # When you change the value of name, the following method is called automatically. This allows you to change the value of the property @name. Setter def name (self, value): If Isinstance (value, basestring): Self._name = VA Lue else:self._name = ' No name ' #获取值 @name. Getter def get (self): return self.name @p  Roperty def: Return Self._age @age. Setter def age (self, value): If value > 0 and value < 100:self._age = value Else:self._age = 0 @property def color (self): Retu RN Self._color @color. Setter def color (self, value): Self._color = Value;a = Animal (' Black Dog ', 3) A.name = ' White Dog ' a.age = 55a.color = ' Red ' Print (' Name: ', a.name) print (' Age: ', a.age) print (' Color: ', a.color) print (a.get) Run Result:Name:white Dogage:55color:redwhite Dog 
5. Slicing and indexing within a class

Magic methods GetItem,setitem and delitem
1. Actions on a list

class Student(object):    def __init__(self, name, scores):        self.name = name        self.scores = scores    # 支持索引; s[index]    def __getitem__(self, index):        # print("获取索引对应的value值")        return  self.scores[index]    # s[索引] = 修改的值    def __setitem__(self, index, value):        self.scores[index] = value    # del s[索引]    def __delitem__(self, index):        del self.scores[index]    def hello(self):        return  "hello"s = Student(‘westos‘, [101, 100, 100])# *********************************索引**************************print(s[0])print(s[1])print(s[2])#更改值s[0] = 200print(s[0])print(s.scores)#删除值del s[0]print(s.scores)# *********************************切片**************************print(s[1:3])s[1:3] = [0,0]print(s[:])del s[:-1]print(s[:])print(s[0])运行结果:101100100200[200, 100, 100][100, 100][100][100, 0, 0][0]0

2. Operation of the Dictionary

class Student(object):    def __init__(self, name, scores):        self.name = name        self.scores = scores    # 支持索引; s[key]    def __getitem__(self, key):        # print("获取索引对应的value值")        return  self.__dict__[key]    # s[key] = 修改的值    def __setitem__(self, key, value):        self.__dict__[key] = value    # del s[key]    def __delitem__(self, key):        del self.__dict__[key]    def hello(self):        return  "hello"s = Student(‘westos‘, [101, 100, 100])#**************************key获取value值***********************print(s.__dict__)print(s[‘name‘])print(s[‘scores‘])s[‘name‘] = ‘westo1‘print(s[‘name‘])del s[‘name‘]   #删除一个键值对# print(s[‘name‘])  #如果查值,会报错:key不存在运行结果:{‘name‘: ‘westos‘, ‘scores‘: [101, 100, 100]}westos[101, 100, 100]westo1
6.Call () method

When a class implements the call method, an instance of the class becomes a callable object. That is the function.
1.

class ClassA:    def __call__(self, *args, **kwargs):        print(‘call ClassA instance.......‘)# ClassA实现了__call__方法a = ClassA()#这个时候,ClassA的实例a,就变成可调用对象#调用a(),输出call ClassA instance,说明是调用了__call__函数a()# 其实a()等同于a.__call__(),它本质上就是后者的缩写a.__call__()运行结果:call ClassA instance.......call ClassA instance.......

2.

class Dddd(object):  def __init__(self, origin):    self.origin = origin    print("origin :"+str(origin))  def __call__(self, x):    print("x :"+str(x))p = Dddd(100)p(2000)运行结果:origin :100x :2000
7. Implement a singleton mode
class Student(object):    def __init__(self, name, scores, power):        self.name = name        self.scores = scores        self.power = power    # 实例化对象之前先执行下面这个new魔术方法    def __new__(cls, *args, **kwargs):        # 判断是否obj对象是否已经被创建, 如果没有被创建, 则创建,        if not hasattr(cls, ‘obj‘):            cls.obj = object.__new__(cls)        # 如果已经创建成功,则返回创建好的对象        return  cls.objs1 = Student(‘westos1‘, [101,100,100], 100)s2 = Student(‘westos1‘, [101,100,100], 100)print(s1)print(s2)运行结果:<__main__.Student object at 0x7fedfa2ebef0><__main__.Student object at 0x7fedfa2ebef0>

As you can see, the objects s1,s2 the same address they point to, that is, they are the same object. Instead of two objects of the same value.

8. Security context with statement in class

Enter () and exit()

class MyOpen(object):    def __init__(self, filename, mode=‘r‘):        self._name = filename        self._mode = mode    # 当with语句开始运行的时候,执行此方法;    def __enter__(self):        self.f = open(self._name, self._mode)        return  self.f    # 当with语句执行结束之后运行;    def __exit__(self, exc_type, exc_val, exc_tb):        self.f.close()with MyOpen(‘/etc/passwd‘) as f:    print(f.closed)    print(f.read(5))print(f.closed)运行如果:Falseroot:True
9. Reflection

Reflection: The ability (introspection) of a program to access, detect, and modify its own state or behavior.
Python-oriented reflection in objects: manipulating Object-related properties in the form of strings. Everything in Python is an object (you can use reflection). That is, let the object tell us the relevant information (the properties and methods owned by the object, the class to which the object belongs, etc...)

Four functions that can be self-reflective

Hasattr (Object,name)
Determine if there is a method or property in the object that has a name string, and note that the private property or method cannot be judged
GetAttr (object, name, Default=none)
Gets whether there are any corresponding methods and properties in the object, and the private property or method cannot be judged to be available. Default is to set the return value when it is not available and defaults to none
SetAttr (x, y, v)
Modify or add an object's properties
Delattr (x, y)
Delete the properties of a class or object

Class Student (object): "" "This is the help document for the Student class" "Def __init__ (self, Name, age): Self.name = name S Elf.__age = Age def Get_score (self): return "score" Def Get_grade (self): return ' grade ' S1 = Student (" Fentiao "," Print (Type (S1)) print (Isinstance (S1, Student)) print (isinstance (' Hello ', Student)) # with the contents of the object can be obtained print (S1 . __class__) #类信息print (s1.__dict__) #生成字典print (s1.__doc__) #获取帮助文档 # hasattr, GetAttr, SetAttr, delattr# hasattr: Determine if the object Contains the corresponding property or method name; print (hasattr (S1, ' name ')) print (Hasattr (S1, ' __age ')) # Private property, private method, cannot be judged; print (hasattr (S1, ' score ')) Print (Hasattr (S1, ' Get_score ')) print (Hasattr (S1, ' Set_score ')) # Getattrprint (GetAttr (S1, ' name ')) print (GetAttr (S1, ' __age ', ' no attr ') print (GetAttr (S1, ' get_score ', ' no method ') # Gets the method name, and if you want to execute the method, direct call can print (GetAttr (S1, ' Set_score ', ' No method ') # Gets the method name, if you want to execute the method, call it directly # setattr:# modify the value of a property setattr (S1, ' name ', ' Westos ') print (GetAttr (S1, ' name ')) # Add a property and The corresponding value; SetAttr (S1, ' score ', ") Print (GetAttr (S1, ' score ') # Modify Method Def get_score1 (): Return "This is the method content of the modification" setattr (S1, ' Get_score ', get_score1) print (GetAttr (S1, ' Get_scor E ') ()) def Set_score (): Return "This is the method added" # Add method SetAttr (S1, ' Set_score ', set_score) print (GetAttr (S1, ' Set_score ') ()) # Del Attrdelattr (S1, ' name ') print (hasattr (S1, ' name ')) print (Hasattr (S1, ' Set_score ')) delattr (S1, ' Set_score ') print ( Hasattr (S1, ' Set_score ')) operation result: <class ' __main__. Student ' >truefalse<class ' __main__. Student ' >{' name ': ' Fentiao ', ' _student__age ': 10} This is the Student class help document Truefalsefalsetruefalsefentiaono Attr<bound Method Student.get_score of <__main__. Student object at 0x7efc6b8a3ac8>>no methodwestos100 This is the method of modifying the contents of the method that is added Falsetruefalse

Python Learning-object-oriented learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.