Python Learning-Customizing classes

Source: Internet
Author: User
#!/usr/bin/env python #-*-coding:utf-8-*-' Custom class ' __author__ = ' Hui.qian ' class Student (object): Def __init__ (sel F,name): Self.name = name s = Student (' Hui.qian ') s print S #添加__str__方法, equivalent to the ToString () class Student in Java (object ): Def __init__ (self,name): self.name = name def __str__ (self): Return ' Student object (name:%s) '% Self.name S1 = Student (' Zuomu.qian ') print ' S1: ' S1 print ' Print S1: ' Print S1 #添加__repr__, knocking directly at the command line S1 displays the same class as print S1 Student (object): Def __init__ (self,name): self.name = name def __str__ (self): return ' Student obje CT (name:%s) '%self.name __repr__ = __str__ s2 = Student (' Zuomu.qian ') s2 print s2 #__iter__迭代方法, objects added to this method can be used for ...
    In Iteration class Calculate_1 (object): Def __init__ (self): self.a=0 def __iter__ (self): return self; Def next (self): self.a +=1 if Self.a>100:raise stopiteration () return SELF.A #fo R N in Calculate_1 (): # priNT N #__getitem__可让上面的类和list一样, the subscript method can be used to remove class calculate_2 (object): Def __getitem__ (self,n): a = 0 f or x in range (n+1): a = x+1 return a f = calculate_2 () print f[1] Print f[3] Print f[0] class Calcula Te_3 (object): Def __getitem__ (self,n): If Isinstance (n,int): a = 0 for x in range (n+1) : a = x+1 elif isinstance (n,slice): L = [] A = n.start B = n.s Top to X in range (b+1): if (x>=a+1): L.append (x) return L F
 1 = calculate_3 () print F1[0:5] #__setitem__对应于dict #__delitem__删除元素

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.