From:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001431865288798deef438d865e4c2985acff7e9fad15e3000
Unlike static languages, Python allows you to bind any data to an instance variable, that is, for two instance variables, although they are different instances of the same class, the name of the variable may be different:
>>> bart = Student (' Bart Simpson ', the)
>>> Lisa = Student (' Lisa Simpson ', ")
>>> Bart . Age = 8
>>> bart.age
8
>>> lisa.age
traceback (most recent called last):
File " <stdin> ", line 1, in <module>
attributeerror: ' Student ' object has no attribute ' age '
If you want internal properties to not be externally accessible, you can add a two underscoreto the name of the attribute. In Python, the instance's variable name, if it starts with __, becomes a private variable (private), accessible only internally and inaccessible outside, so We change the Student class:
Class Student (object):
def __init__ (self, Name, score):
self.__name = name
Self.__score = Score
def print_score (self):
print ('%s:%s '% (Self.__name, Self.__score))
in Python, variable names like __xxx__, which begin with a double underscore and end with a double underscore, are special variables that can be accessed directly, not private variables, so you can't use variable names such as __name__ and __score__.
Sometimes you'll see an instance variable name that starts with an underscore, for example _name, such an instance variable outside is accessible, but, according to the conventions, when you see such a variable, meaning, "although I can be accessed, but, please treat me as a private variable, do not randomly access."
Whether an instance variable beginning with a double underline must not be accessed from the outside. Not really. __name is not directly accessible because the Python interpreter has changed the __name variable to _student__name, so the __name variable can still be accessed through _student__name:
>>> bart._student__name
' Bart Simpson '
Determining Whether a variable is a type can be judged by isinstance ():
A = List () # A is the list type
b = Animal () # B is the Animal type
c = Dog () # C is the Dog type
>>> isinstance (A, list)
true
>>> isinstance (b, Animal)
true
>>> Isinstance (c, Dog)
True
>>> isinstance (c, Animal)
True
You can also determine whether a variable is one of several types, such as the following code to determine whether it is a list or tuple:
>>> Isinstance ([1, 2, 3], (list, tuple))
True
>>> isinstance ((1, 2, 3), (list, tuple))
True
Python is different from C + + polymorphism is not the keyword "virtual", polymorphism is good to follow the opening and closing principle
Open to expansion: Allow new animal subclasses;
Closed for modification: You do not need to modify functions such as run_twice () that depend on the animal type.
static language vs Dynamic Language
For static languages, such as Java, if you need to pass in a animal type, the incoming object must be a animal type or its subclass, otherwise you will not be able to invoke the run () method.
For dynamic languages like Python, you don't necessarily need to pass in the animal type. All we need to do is make sure that the incoming object has a run () method:
Class Timer (object):
def run (self):
print (' Start ... ')
This is the "duck type" of the dynamic language, which does not require a strict succession system, an object that "looks like a duck, walks like a duck", and it can be considered a duck.
Python's "File-like object" is a type of duck. For a real file object, it has a read () method that returns its contents. However, many objects, as long as they have the read () method, are considered "File-like object". Many functions receive the argument "File-like object", you do not have to pass in the real file object, you can pass in any object that implements the Read () method. type ()
Basic types can be judged by type ():
>>> type (123)
<class ' int ' >
>>> type (' str ')
<class ' str ' >
>> > Type (None)
<type (none) ' Nonetype ' >
If a variable points to a function or class, you can also use type () to determine:
>>> type (ABS)
<class ' Builtin_function_or_method ' >
>>> Type (a)
<class ' __ main__. Animal ' >
>>> type (123) ==type (456)
True
>>> type (' abc ') ==type (123)
False
>>> type (123) ==type (456)
true
>>> type (123) ==int
true
>>> type (' ABC ') ==type (' 123 ')
true
>>> type (' abc ') ==STR
true
>>> type (' abc ') ==type ( 123)
False
The basic data type can be directly written int,str, and so on, but if you want to determine whether an object is a function. You can use constants defined in the types module:
>>> Import Types
>>> def fn ():
... Pass
...
.. >>> type (FN) ==types. Functiontype
True
>>> type (ABS) ==types. Builtinfunctiontype
True
>>> type (lambda x:x) ==types. Lambdatype
True
>>> type ((x for X in range ()) ==types. Generatortype
True
getattr (), SetAttr () and hasattr ( ) you can manipulate the state of an object directly
>>> class MyObject (object):
... def __init__ (self):
... self.x = 9
... def power (self):
... return self.x * self.x ...
>>> obj = MyObject ()
Immediately thereafter, you can test the properties of the object:
>>> hasattr (obj, ' x ') # has attribute ' x '.
True
>>> obj.x
9
>>> hasattr (obj, ' y ') # has attribute ' Y '.
False
>>> setattr (obj, ' y ', 19) # set an attribute ' y '
>>> hasattr (obj, ' y ') # has attribute ' Y '.
True
>>> getattr (obj, ' y ') # get attribute ' y '
>>> obj.y # Get property ' y '
19
If you attempt to obtain a property that does not exist, a attributeerror error is thrown:
>>> getattr (obj, ' z ') # Get Properties ' Z '
traceback (most recent call last):
File "<stdin>", line 1, ;module>
attributeerror: ' MyObject ' object has no attribute ' Z '
you can pass in a default parameter, and if the property does not exist, return the defaults:
>>> getattr (obj, ' z ', 404) # Get property ' Z ', if not present, return default value 404
404
You can also obtain the object's methods:
>>> hasattr (obj, ' power ') # has attribute ' power '.
True
>>> getattr (obj, ' power ') # Gets the property ' power '
<bound method Myobject.power of <__main__. MyObject Object at 0x10077a6a0>>