< turn >python OOP (1): Starting from the basics

Source: Internet
Author: User

Transfer from http://www.cnblogs.com/BeginMan/p/3510786.html

This article aims to review and summarize Python:1. How do I create classes and instances?

# 创建类class ClassName(object):    """docstring for ClassName"""    def __init__(self, arg):        super(ClassName, self).__init__()        self.arg = arg# 创建实例instance = ClassName()      
2. What is the difference between classic class and new type? 3. What is a method? How is it defined? How do I use it?

method is the function of the class
defined in the class
Invoking through an instance

4. What does self represent? Where to use?

Each class method has a self parameter that represents the instance object itself , which is silently passed to the method by the interpreter when the instance invokes the method, without the manual self coming in.
Self is not a keyword in python. Self represents the address of the current object. Self can avoid global variables caused by unqualified calls.
Why in Wangkangluo1 's Python is it clear to self:

Create a class MyClass, instantiate MyClass get MyObject this object, and then call this object method Myobject.method (ARG1,ARG2), in this process, Python will automatically switch to Myclass.mehod ( MYOBJECT,ARG1,ARG2)
This is the principle of the self of Python. Even if the method of your class does not require any arguments, you will have to define a self parameter for this method.

5. Two kinds of operations for class objects?

After the class is defined, the class object is created, and the class object supports two operations: Reference and instance
Reference: A Class object that invokes a property or method in a class; instance: An entity that instantiates a class object through a class object.

6. What are Python class properties and instance properties?

property is the data or function element of another object! accessed through a period symbol, such as some python types such as complex numbers with data attributes , lists and dictionaries that have methods ( function Properties ). It is also possible that when a property is accessed, the property is an object, and it has its own properties, which makes up the attribute chain . Such as:

>>> import sys>>> sys.stdout.write(‘beginman‘)beginman>>> myMoudel.myClass.__doc__

Class properties are related to the class, regardless of the instance, usually the data properties of the class, just the variables defined in the class, often referred to as static variables or static data. In other languages, the equivalent is preceded by a variable static .

>>> class C(object):    foo = 100  # 定义类属性>>> print C.foo # 访问类属性100>>> C.foo = C.foo+100 # 更新类属性>>> C.foo200

As you know, class properties are only related to classes (classes are objects, Python is called Class objects), and there is no relationship with the instance half-dime.

>>> class C(object):    foo = 100  # 定义类属性>>> print C.foo # 访问类属性100>>> C.foo = C.foo+100 # 更新类属性>>> C.foo200>>> c=C()  # 实例化一个对象c>>> c.foo200>>> c.foo = 1000  # 实例试图修改类属性>>> c.foo # 实例想看是否修改成功,于是就c.foo竟输出1000,于是实例就满以为自己成功了1000>>> C.foo # 类对象鄙夷的看了实例一样,说:“你就是老子生出来的,老子的东西你也能碰??”200>>> del c.foo # 实例看完之后当场傻眼,心想mlgb,你牛B,我还是除掉自己负担沉重的改造吧>>> c.foo  
7, class method?
>>> class C (object): foo = def met (self): The print ' I am method for class. ' >>> C.met () # C I thought the method is also a part of me, then the method is also the Class property * (This is correct), so I call you to play Traceback (most recent called last): File "&LT;PYSHELL#31&G t; ", line 1, in <module>c.met () # C I thought the method is also a part of me, then the method is also a class property * (This is correct), so I call you to play Typeerror:unbound method met () must be CA Lled with C instance as first argument (got nothing instead) >>> # It's a big deal, and the method doesn't agree with the >>> # I thought it was for what? It suddenly occurred to me that the bird man python>>> # Bird man Guido van Rossum to create the Python class gives the rule that you can create a class method, but not to flirt with her. >>> c=c () # class Heart is unwilling, so created an example of small C to tyrant >>> C.met () # Instance small C thought, MLGBD, the last time you want to modify the class properties you mercilessly despised a, now and embarrassed me, alas, commiseration. Anyway, try it. I am method for class.>>> # Nasty, class method unexpectedly listen to my instance, so the instance hurriedly find Guido van Rossum ask what situation >>> # Guido van Rossum said "for Consistent with the OOP conventions, no instance can not invoke the method, which is the binding concept that Python describes, the method must be bound in the instance to be obedient, can not give the right to the class, this is Lao Tzu's favor of your example. ">>> # example after listening to tears cow face, class objects angry, said:" Today, I will take all the parts of my body (attributes) out to see, see who is not obedient! ">>> dir (C) # So the class object uses the first stroke of Dir () built [' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module__ ', ' __new__ ', ' __reduce__ ', ' __ Reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' foo ', ' met ']> >> Print c.__dict__ # The second trick is to summon his most obedient attribute __dict__ to pull out {' __module__ ': ' __main__ ', ' met ': <function met at 0x0000000002 D33eb8>, ' __dict__ ': <attribute ' __dict__ ' of ' C ' objects>, ' foo ': +, ' __weakref__ ': <attribute ' __weakref_  _ ' of ' C ' objects>, ' __doc__ ': none}>>>
After the class object is out of the limelight, it is the instance:

The creation of the instance:
C + + and other programming applications, the instance object is New out, Python cow B, just like others, partial to the form of function call instantiation.

class CC(object):    #我是Python类默许的,没重写__init__,所以也没有什么特殊操作    passclass C(object):    def __init__(self,name,phone,ID):        super(C,self).__init__()        self.name = name        self.phone = phone        self.id = ID        print ‘Hi man 我重写了__init__,因为我需要更多的操作‘cc = CC() # 创建CC实例c = C(‘BeginMan‘,‘110‘,‘12306‘) # 创建C实例

Highlights::
When a class is called, the first step in instantiation is to create an instance object, and then Python checks to see if the method is implemented __init__() , and by default no __init__ special action is applied without overwriting. Any special operations need to be rewritten __init__ .
Then pass the parameter, which depends on your own definition __init__ , it has how many parameters, in the process of instantiation to pass how many parameters, regardless of whether or not overwrite __init__() , the instance object to be passed in as the first parameter.

__init__And __new__ , __call__ the difference:

__new__More like a real constructor, called when an object is created, returns an instance of the current object. But the actual use of very little.
__init__: Initializes the work, calls when the object is created, initializes an instance of the current object, and no return value . It's very common in Python.
__call__: To let instances of classes behave like functions, you can call them, pass a function as one parameter to another function, and so on. Rarely used.
Priority: __new__ first with__init__

__del__destructor method, see "py core"

Instance properties:

It can be created at any time after the instance is created, or at run time. __init__() Is the key point for creating these properties.

>>> c.__dict__  # 此时实例c还没属性{}>>> c.__class__ # 实例化的类<class ‘__main__.C‘>>>> c.foo=1>>> c.name=‘CS‘>>> c.__dict__{‘foo‘: 1, ‘name‘: ‘CS‘}>>> dir(c)[***‘foo‘, ‘name‘***,‘__class__‘, ‘__delattr__‘, ‘__dict__‘, ‘__doc__‘, ‘__format__‘, ‘__getattribute__‘, ‘__hash__‘, ‘__init__‘, ‘__module__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘__weakref__‘]
What are the similarities and differences between Python object-oriented and other languages?

Similar
Differences between "Java oop" and "Pythonic oop"?
True TM's tongue, who English good can translate under.

What is a constructor, __init__What does it say? What's the point?

Reference to object-oriented programming init method

Common terms for OOP

This is often seen in software engineering, because Python oop is not too much to use, so the embodiment of OOP features is not so obvious, c++/java/c# oop thought is quite deep, but I too dishes, difficult to familiar with the essence of OOP.
Summary of common terms in object-oriented programming
The pair also includes introspection .

What is Python introspection (reflection)?

Recommended Reading

Next issue: Python OOP advanced.

< turn >python OOP (1): Starting from the basics

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.