"Python" "Object Oriented"

Source: Internet
Author: User


# "Object-oriented" "
# "Access Restrictions"
#如果要让内部属性不被外部访问, you can add double underlines and program private variables. Only the internal can be accessed and externally inaccessible.
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))
Bart = Student (' Bart Simpson ', 66)
#print (bart.__name) #AttributeError: ' Student ' object has no attribute ' __name '
#如果想让外部代码获取name score can be as follows
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))
def get_name (self):
Return Self.__name
def get_score (self):
Return Self.__score
#允许外部代码修改
def set_score (Self,score):
If 0 <= score <= 100:
Self.__score = Score
Else
Raise ValueError (' Bad score ')
# "Note" __name__ is a special variable that can be accessed directly, not as a private variable, so a variable name such as __name__ cannot be used.
# an underscore that can be accessed externally, but in accordance with the conventional, if you encounter this, it is private.
# The reason why the double underline cannot be accessed directly, the Python interpreter has changed __name to _student__name, so the __name variable can still be accessed through _student__name.
Print (bart._student__name) #Bart Simpson
# but it is highly recommended not to do this because different versions of the Python interpreter may change the __name to a different variable name.
#注意下面错误写法
Bart = Student (' Bart Simpson ', 66)
Print (Bart.get_name ()) #Bart Simpson
Bart.__name = ' New name '
Print (bart.__name) #New name "Note" At this time the __name and the __name inside the class are not the same, the internal has been automatically changed to the Python interpreter _student__name, external code to the Bart object A new __name variable has been added
Print (Bart.get_name ()) #Bart Simpson

# "Inheritance & Polymorphism"
#继承可以把父类所有功能直接拿过来 so that you do not have to start from scratch. Subclasses only need to add their own methods, or override overridden methods that are not appropriate for the parent class.
#动态语言的鸭子类型决定了继承不像静态语言那样是必须的.


# "Get Object Info"
# 1 using the type () to determine the basic data type can be directly written int str and so on. If you want to determine if it is a function, you can use a constant defined in the types module.
Import types
DEF fn ():
Pass

Print (Type (fn) = = types. Functiontype) #True
Print (type (ABS) = = types. Builtinfunctiontype) #True
Print (Type (lambda x:x) = = types. Lambdatype) #True
Print (Type (x for x in range) = = types. Generatortype) #True

# 2 using Isinstance () can be used with the type () isinstance () but the available isinstance () may not necessarily be replaced with type ()
Print (isinstance (' + ', str)) #True
Print (Isinstance (lambda x:x), types. Lambdatype)) #True

Class Animal (object):
def run (self):
Print (' animal is running.. ')
Class Dog (Animal):
def run (self):
Print (' dog is running. ')
Class Hushy (Dog):
def run (self):
Print (' Hushy is running.. ')

A = Animal ()
D = Dog ()
h = hushy ()
Print (type (d) = = Dog) #True
Print (type (d) = = Animal) #False
Print (Isinstance (d,dog)) #True
Print (Isinstance (d,animal)) #True
Print (Isinstance (h,animal)) #True
Print (Isinstance (d,hushy)) #False
#还可以判断一个变量是否是某些类型中的一种.
Print (Isinstance ([i], (list,tuple))) #True

# "Summary" always takes precedence over isinstance (), the specified type and its subclasses can be "clean sweep"

# 3 Use Dir () to get all the properties and methods of an object.
Print (dir (' ABC ')) #[' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __init_subclass__ ' ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' capitalize ', ' casefold ' ', ' center ', ' count ', ' encode ', ' endswith ', ' expandtabs ', ' find ', ' format ', ' Format_map ', ' index ', ' isalnum ', ' isalpha ', ' Isdecimal ', ' isdigit ', ' isidentifier ', ' islower ', ' isnumeric ', ' isprintable ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' Ljust ', ' lower ', ' lstrip ', ' Maketrans ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' rstr ' IP ', ' Split ', ' splitlines ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']
#仅仅是把属性和方法列出来是不够的, with GetAttr () SetAttr () 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 ()

Print (hasattr (obj, ' x ')) #True
Print (obj.x) #9
Print (hasattr (obj, ' y ')) #False
SetAttr (obj, ' y ', 19)
Print (hasattr (obj, ' y ')) #True
Print (GetAttr (obj, ' y ')) #19
Print (OBJ.Y) #19
#如果试图获取不存在的属性, throw Attributeerror
#print (getattr (obj, ' z ')) #AttributeError: ' MyObject ' object has no attribute ' Z '
#可传一个default参数, returns the default value if the property does not exist
Print (GetAttr (obj, ' z ', 404)) #404
#也可以获得对象的方法
Print (hasattr (obj, ' power ')) #True
Print (GetAttr (obj, ' power ')) #<bound method Myobject.power of <__main__. MyObject Object at 0x102a36470>>
#获取属性power并赋值到变量fn
fn = getattr (obj, ' power ')
Print (FN) #<bound method Myobject.power of <__main__. MyObject Object at 0x1022364a8>>
Print (FN ()) #81

‘‘‘
Get object Information

reads: 214832
When we get a reference to an object, how do we know what kind of object it is and what methods it has?

Use Type ()

First, let's determine the object type, using the type () function:

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, it can also be judged with type ():

>>> Type (ABS)
<class ' Builtin_function_or_method ' >
>>> type (a)
<class ' __main__. Animal ' >
But what type is returned by the type () function? It returns the corresponding class type. If we are to judge in an if statement, we need to compare the type of the two variables with the same types:

>>> 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, etc., but what if you want to determine if an object is a function? You can use the 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
Using Isinstance ()

The use of type () is inconvenient for class inheritance relationships. To determine the class type, we can use the isinstance () function.

We review the last example, if the inheritance relationship is:

Husky, Dog, Animal, Object---
So, isinstance () can tell us whether an object is of a certain type. Create 3 types of objects First:

>>> a = Animal ()
>>> d = Dog ()
>>> h = Husky ()
Then, Judge:

>>> isinstance (H, Husky)
True
No problem, because the H variable is pointing to the Husky object.

To judge again:

>>> isinstance (H, Dog)
True
H is a husky type, but since husky is inherited from dog, H is also a dog type. In other words, isinstance () determines whether an object is the type itself, or is on the parent inheritance chain of that type.

So, we can be sure that H is still the animal type:

>>> isinstance (H, Animal)
True
Similarly, the actual type is dog's D and animal type:

>>> Isinstance (d, Dog) and Isinstance (d, Animal)
True
However, D is not a husky type:

>>> Isinstance (d, Husky)
False
The basic type that can be judged by type () can also be judged by isinstance ():

>>> isinstance (' a ', str)
True
>>> Isinstance (123, Int.)
True
>>> Isinstance (b ' a ', bytes)
True
You can also determine whether a variable is one of some types, such as the following code to determine whether it is a list or a tuple:

>>> Isinstance ([1, 2, 3], (list, tuple))
True
>>> Isinstance ((1, 2, 3), (list, tuple))
True
Always use Isinstance () to determine the type, and you can "clean sweep" The specified type and its subclasses.
Use Dir ()

If you want to get all the properties and methods of an object, you can use the Dir () function, which returns a list that contains a string, for example, to get all the properties and methods of a str object:

>>> dir (' ABC ')
[' __add__ ', ' __class__ ',..., ' __subclasshook__ ', ' capitalize ', ' casefold ',..., ' 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 Mydog (object):
... def __len__ (self):
... return 100
...
>>> dog = Mydog ()
>>> Len (dog)
100
All that is left is a normal property or method, such as lower () that returns a lowercase string:

>>> ' ABC '. Lower ()
' ABC '
It is not enough to simply list properties and methods, with GetAttr (), SetAttr (), and hasattr (), we 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 ') # 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
If you try to get a property that does not exist, you throw a attributeerror error:

>>> getattr (obj, ' z ') # get property ' Z '
Traceback (most recent):
File "<stdin>", line 1, in <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) # Gets the property ' Z ', returns the default value 404 if it does not exist
404
You can also get the method of the object:

>>> hasattr (obj, ' power ') # have attribute ' power '?
True
>>> getattr (obj, ' power ') # Get property ' power '
<bound method Myobject.power of <__main__. MyObject Object at 0x10077a6a0>>
>>> 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 0x10077a6a0>>
>>> fn () # call FN () is the same as calling Obj.power ()
81
Summary

With the built-in series of functions, we can parse any Python object and get its internal data. It is important to note that we only get object information when we do not know the object information. If you can write directly:

sum = obj.x + obj.y
Don't write it:

sum = getattr (obj, ' x ') + getattr (obj, ' y ')
An example of the correct usage is as follows:

def readimage (FP):
If Hasattr (FP, ' read '):
return ReadData (FP)
Return None
Assuming that we want to read the image from the file stream FP, we first determine whether the FP object has a read method, and if so, it is a stream and cannot be read if it does not exist. Hasattr () comes in handy.

Note that in a dynamic language such as Python, the Read () method, depending on the duck type, does not mean that the FP object is a file stream, it may be a stream of the network, or it may be a byte stream in memory, but as long as the Read () method returns valid image data, it does not affect the ability to read the image.

‘‘‘

# "Instance Properties & Class Properties"
#可以为实例绑定任何属性和方法, this is the flexibility of dynamic language.

# "__slots__"
# Normally, when we define a class and create a class instance, we can bind any property and method to that instance, which is the flexibility of dynamic language.
Class Student (object):
Pass
s = Student ()
S.name = ' Michael '
Print (S.name)
Binding a method #还可以给 instance
def set_age (self,age):
Self.age = Age
From types Import Methodtype
S.set_age = Methodtype (set_age,s)
S.set_age (25)
Print (s.age) #25
#但是, the method that is bound to one instance does not work for another instance
S2 = Student ()
#s2. Set_age (#AttributeError): ' Student ' object has no attribute ' set_age '
#为了给所有实例di

































"Python" "Object Oriented"

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.