Python learns Day 8 inherits polymorphic Type isinstance dir __slots__

Source: Internet
Author: User
Tags instance method

Inheritance and polymorphism

In OOP programming, when we define a class, we can inherit from an existing class, the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base class, superclass).

>>> class Animal (object): #名为Animal的class

Defrun (self):

print ' Animal is running ... '

>>> class Dog (Animal): #从Animal类继承

Pass

>>> Dog=dog ()

>>> Dog.run () #子类获得了父类的全部功能

Animal is running ...

>>> class Dog (Animal): #对子类增加一些方法

Defrun (self):

print ' Dog is running ... '

>>> Dog=dog ()

>>> Dog.run ()

Dog is running ...

Polymorphic

A = List () # A is a list type

b = Animal () # B is the Animal type

c = Dog () # C is the dog type

>>> isinstance (A, list)

True

In an inheritance relationship, if the data type of an instance is a subclass, its data type can also be considered a parent class. However, the reverse is not possible:

>>> B = Animal ()

>>> Isinstance (b, Dog)

False

Inheritance can take all the functions of the parent class directly, so that you do not have to re-zero, subclasses only need to add their own unique methods, but also the parent class does not fit the method overrides overrides, with inheritance, can be polymorphic. When invoking the class instance method, as far as possible the variable as the parent class type, so that all subclass types can be properly received;

Use Type ()

To determine the object type, use the type () function:

>>> type (123) #基本类型都可以用type () judgment

<type ' int ' >

>>> type (' str ')

<type ' str ' >

>>> type (None)

<type ' Nonetype ' >

>>> type (ABS) #变量指向函数或者类, can also be judged by type ()

<type ' Builtin_function_or_method ' >

>>> type (a)

<class ' __main__. Animal ' >

>>> type (123) ==type (456) #比较两个变量的type类型是否相同

True

>>> Import Types#python defines constants for each type, placed in the types module

>>> type (' abc ') ==types. StringType

True

>>> type (U ' abc ') ==types. Unicodetype

True

>>> type ([]) ==types. ListType

True

>>> type (str) ==types. Typetype

True

>>> type (int) ==type (str) ==types. Special types of typetype#

True

using Isinstance ()

Isinstance () can tell us whether an object is of a certain type. He determines whether an object is the type itself, or is on the parent inheritance chain of that type.

>>> Isinstance (d, Dog) and Isinstance (D,animal)

True

>>> isinstance (' a ', str)

true# can be judged by type () or by Isinstance ().

>>> isinstance (' A ', (str, Unicode))

true# determine if a variable is one of some types

>>> isinstance (U ' a ', basestring)

True#str and Unicode are inherited from Basestring.

Use Dir ()

>>> dir (' ABC ') #获得一个str对象的所有属性和方法

[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr __ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ' , ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' _ Formatter_field_name_split ', ' _formatter_parser ', ' capitalize ', ' center ', ' count ', ' decode ', ' encode ', ' endswith ', ' Expandtabs ', ' find ', ' format ', ' Index ', ' isalnum ', ' isalpha ', ' isdigit ', ' islower ', ' isspace ', ' istitle ', ' isupper ', ' Join ', ' ljust ', ' lower ', ' lstrip ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' splitlines ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']

__xxx__-like properties and methods are used in Python for special purposes, such as the __len__ method returns the length. In Python, if you call the Len () function to try to get the length of an object, in fact, inside the Len () function, it automatically calls the __len__ () method of the object, so the following code is equivalent:

>>> len (' ABC ')

3

>>> ' ABC '. __len__ ()

3

We write our own class, if we want to use Len (MYOBJ), we write a __len__ () method:

>>> class MyObject (object):

Def__len__ (self):

Return 100

>>> obj = MyObject ()

>>> Len (obj)

100

With GetAttr (), SetAttr (), and hasattr (), we can manipulate the state of an object directly:

Class MyObject (object):

Def__init__ (self):

self.x = 9

Defpower (self):

Return self.x * self.x

>>> hasattr (obj, ' x ') # have attribute ' x '?

True

>>> obj.x

9

>>> hasattr (obj, ' y ') # have attribute ' y '?

False

>>> setattr (obj, ' y ', 19) # Set a property ' Y '

>>> hasattr (obj, ' y ') # have attribute ' y '?

True

>>> getattr (obj, ' y ') # Get property ' Y '

19

>>> obj.y # Get property ' Y '

19

>>> getattr (obj, ' z ', 404) # Gets the property ' Z ', returns the default value 404 if it does not exist

404

>>> hasattr (obj, ' power ') # have attribute ' power '?

True

>>> getattr (obj, ' power ') # Get property ' power '

<bound method Myobject.power of<__main__. MyObject Object at 0x108ca35d0>>

>>> fn = getattr (obj, ' power ') # Gets the property ' power ' and assigns a value to the variable fn

>>> FN # fn points to Obj.power

<bound method Myobject.power of<__main__. MyObject Object at 0x108ca35d0>>

>>> fn () # call FN () is the same as calling Obj.power ()

81

Using __slots__

>>> class Student (object):

Pass

>>> s = Student ()

>>> s.name = ' Michael ' # dynamically binds an attribute to an instance

>>> Print S.name

Michael

>>> def set_age (self, Age): # define a function as an instance method

Self.age = Age

>>> from types Import Methodtype

>>> s.set_age = Methodtype (Set_age, s,student) # Bind a method to an instance

>>> S.set_age (25) # Invoke instance method

>>> S.age # Test Results

25

However, the method that is bound to one instance does not work for another instance:

>>> s2 = Student () # Create a new instance

>>> S2.set_age (25) # Try to call a method

Traceback (most recent):

File "<stdin>", line 1, in <module>

Attributeerror: ' Student ' object has no attribute ' set_age '

To bind a method to all instances, you can bind the method to class:

>>> def set_score (self, score):

... self.score = Score

...

>>> Student.set_score = Methodtype (Set_score,none, Student)

When you bind a method to a class, all instances are callable:

>>> S.set_score (100)

>>> S.score

100

>>> S2.set_score (99)

>>> S2.score

99

For the purpose of limiting, Python allows you to define a special __slots__ variable when defining a class to limit the attributes that the class can add:

>>> class Student (object):

__slots__ = (' name ', ' age ') # defines the name of the property allowed to bind with a tuple

>>> s = Student () # Create a new instance

>>> s.name = ' Michael ' # binding attribute ' name '

>>> s.age = 25 # Binding attribute ' age '

>>> s.score = 99 # binding attribute ' score '

Traceback (most recent):

File "<stdin>", line 1, in <module>

Attributeerror: ' Student ' object has no attribute ' score '

Because ' score ' is not placed in __slots__, the score property cannot be bound, and attempting to bind score will get attributeerror error.

Use __slots__ Note that the properties defined by __slots__ only work for the current class and do not work with inherited subclasses:

>>> class Graduatestudent (Student):

... pass

...

>>> g = graduatestudent ()

>>> G.score = 9999

Unless __slots__ is also defined in a subclass, the subclass allows the defined property to be its own __slots__ plus the __slots__ of the parent class.

Python learns Day 8 inherits polymorphic Type isinstance dir __slots__

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.