Python object-oriented advanced programming-__slots__, custom classes, enumerations

Source: Internet
Author: User

How do classes in Python restrict the properties of an instance when various attributes are defined in the class, and the outside can be arbitrarily added?

Python comes with a lot of custom classes, such as __slots__,__str__

__slots__

The __slots__ method is to define the properties for the instance when the class is created.

classStudent (Object): __slots__=('name',' Age') Pass>>>s =Student ()>>>s.name='Tom'>>>s.age=' Age'>>>s.score=Ten#AttributeError:'Student' Objecthas no attribute'score'

When the __slots__ has been qualified, then to the instance binding has no qualified properties, will be error.

The __slots__ scope is limited to the current class, and when there is a __slots__ attribute in the parent class, there is no restriction in the subclass, and when __slots__ is defined in the subclass, the instance limit of the subclass is the subclass itself plus the __slots__ of the parent class.

__str__ and __repr__

If you want to turn an instance of a class into str, you need to implement a special Method __str__ ():

 class person (object):  def __init__(self, Name, gender): Self.name 
     = name Self.gender = gender  def __str__(self):  ret Urn '(person:%s,%s)' % (Self.name, Self.gender)

>>>p = person (' tom ', ' Male ')
>>>print (P)
(Person:tom,male)
>>>p #直接打印p __str__ will not be called
<main. Person object at 0x10c941890>

Because Python defines __str__ () and __repr__ ( ) Two methods, __str__ () is used to display to the user, and __repr__ () is used to display to developers.

There's a lazy way to define __REPR__:

class Person (object):     def __init__ (self, Name, gender):         = name        = gender    def__str__(self):        return  '(person:%s,%s)' % (self.name, Self.gender)    __repr__  __str__

__len__

If a class behaves like a list, the len () function is needed to get the number of elements.

For the len () function to work properly, the class must provide a special method, __len__ (), which returns the number of elements.

For example, we write a Students class that passes the name in:

class Students (object):     def __init__ (Self, *args):         = args    def__len__(self):        return len (self.names)

>>>s = Student (' A ', ' B ', ' C ') #只要正确实现了 the __len__ () method, you can return Students with the len () function the "Length" of the instance
>>>print Len (s)
3

__call__

All of Python's functions are callable objects.

An instance of a class can also become a callable object, just to implement a special method __call__ ().

We turn the person class into a callable object:

 class Person  (object):  def __init__(self, Name, sex): Self.name = name Self.sex = sex  def __call__(self, Friend):  pri NT ('My name is%s ... ' % self.name ' print('My Friend is%s ... ' % friend)

>>>p = person (' Tom ', ' Boy ')
>>>p (' Jerry ') #对实例直接调用
My name is Tom
My Friend is Jerry

Enumeration

Defines an enum that introduces the module enum, which enumerates classes that inherit the enum class

 from Import Enum class Book (Enum):     = 1    = 2    = 3    = 4    C+ + = 5

There are many ways to access enumerations

>>>book.a<book.a:1>>>>book (1)<Book.a:1>>>>Print  (book.a) book.a>>>Print(book (1)) book.a>>>book.a.name ' a '>>>book.a.value1

If the member name in the enumeration is duplicated, the error typeerror:attempted to reuse key: ' A '

The value of a member is allowed to be duplicated, but is also the first member property when accessed, and Python considers the second member of the duplicate as the first alias

 from Import Enum class Book (Enum):     = 1    = 1>>>book.a<Book.a:1>>>>book.b  #访问b也变成了打印a属性, B is treated as an alias of a
<Book.a:1>

If the restriction enumeration is not duplicated, a unique module is introduced, and the unique is a class adorner, which is used to constrain the value

 from Import Enum,unique@unique class Book (Enum):     = 1    = 1>>>printin'book' >:b A

Enumerate support iterators

>>> for in book :        print(b) book.a 、...

When a member value is duplicated, only the first member is available, to list all, regardless of repetition, use the __members__ method

 fromEnumImportEnumclassBook (Enum): a= 1Math= 2中文版= 3Linux= 4C+ + = 5 forBinchBook.__members__. Items ():Print(b)#print in tuple form('a',<book.a:1>), ('Math',<book.math:2>) 、、、

Python object-oriented advanced programming-__slots__, custom classes, enumerations

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.