Object Oriented python

A, Python classic class and the new class

Classic: If there are no direct or indirect subclass of an object, that is, if you do not specify a parent class or subclass if the base class has no parent, then it is the classic definition of class:

class classics:
    'define a classics Class'
    pass

 

The new categories: In contrast to the classic category. object is the "mother of all classes", that is the base class, if your class does not inherit any parent class object as the default parent class:

class newClass(object):
    'define a classics Class'
    pass

 

Two, Python instantiation

Create an instance of the process is called instantiation, usually with the keyword new, but do not have this keyword in Python in other programming languages. But a similar manner to create an instance of the function call:

class newClass(object):
    pass

inst = newClass()
print inst      #<__main__.newClass object at 0x00B71650>

 

Third, the most simple usage

The simplest use of the class name space is only used as a means to save the data to a variable, use a period attribute identifies them by name space group.

Copy the code
newClass class (Object): 
    Pass 

bar = newClass () # Create instance 
bar.x = 1 # Create Instance Attribute 
bar.y = 2 
Print bar.x + bar.y
Copy the code

Note: bar.x, bar.y instance of an object is not a property of the class attributes.

 

Fourth, the method

The method is functional class

Methods defined in the class, instance can only be invoked.

In class, the process parameter has a default self, this parameter is itself a representative example, when the method call instance, by an interpreter quietly passed to the method.

Copy the code
class newClass(object):
    def method(self):
        return self
    
bar = newClass()
print bar.method()  #<__main__.newClass object at 0x00B71910>
Copy the code

In other languages, self generally referred to this, the general method used in this example would be (self), but static methods and class methods do not.

 

Fifth, create classes, methods, instance object access

Copy the code
the addPerson class (Object): 
    DEF the __init __ (Self, nm, pH): # define constructor 
        self.name = nm # Set name 
        self.phone pH = # Set Phone 
        Print 'the Created for instance', the self.name 
    DEF updatePhone (Self , newph): 
        self.phone = newph 
        Print 'Updated for Phone', self.phone 
        
josn the addPerson = ( 'the JSON', '1,565,208,444') # create an instance josn 
Ben the addPerson = ( 'Ben', '15,249,638,892') # Create examples of objects Ben 
Print 'instance property: [S%] [% S]'% (ben.name, ben.phone) # instance properties 
ben.updatePhone ( '110') 
Print ben.phone
Copy the code

 

Sixth, the subclass

Create a subclass: by inheritance to subclass, improving their function without affecting the parent class (base class) basis.

Such as: inherited class above

Copy the code
class addInfo (addPerson): 
    DEF __init __ (Self, nm, ph, the above mentioned id, EM): # define your own constructor 
        addPerson .__ init __ (self, nm , ph) # inherit the parent class constructor (this is very important) 
        self.empid ID = 
        self.email EM = 
        
    DEF updateEmail (Self, newem): 
        self.email = newem 
        Print 'for Updated E-mail address:', the self.name 
        
zhangsan = addInfo ( 'zhangsan', '123456789', '01', 'zhangSan @ gmail') # Create addInfo instance, the output of the created instance for zhangsan 
Print zhangsan # <__ main __ addInfo Object AT 0x00B71BD0.> 
Print 'instance Property: [% S], [% S], [% S], [% S ] '% (zhangsan.name, zhangsan.phone, zhangsan.empid, zhangsan.email) 
# output: Instance property: [zhangSan], [123456789], [01], [zhangSan @ gmail] 
zhangsan.updatePhone (' 250 ')             #Updated phone for 250
zhangsan.updateEmail('[email protected]')   #Updated e-mail address for: ZhangSan
Copy the code
 

note:

If desired, each subclass best define its own constructor, otherwise, the base class constructor is called. However, if the subclass overrides the base class constructor, then the base class constructor will not be invoked automatically, the job must be explicitly written, as above: addPerson .__ init__

 

one type

Class is a data structure, encapsulating the data and operations.

Disclaimer and function of the class is very similar:

newClass class (Object): 
    "" "Documentation String class" "" # class documentation string 
    class_suite # class body

Note: The class is the object (in Python, everything is an object), but in the definition of class time, not to achieve the object.

 

Second, the class attribute

In object-oriented programming and ideas, the emergence of the concept of class properties.
In java class instance variables , and static variables known as the generic variable (class's variables, often referred to as a class variable ) or a data field (java programming language (Basic) "Machinery Industry Press, p185).
In object-oriented programming language, Python, the class attribute is defined in class variables .
In C ++, the class attribute is a common feature of all of the object class description data items , for instance any object whose property value is the same.
Different programming languages ​​have different definitions. And some languages ​​do not distinguish between static type, so do not use this attribute to indicate whether the static class property. But with modified properties can be static data sharing between objects only.
Properties: function or data elements belong to another object.

In Python is an interesting phenomenon: When visiting a property, it is also an object. Has its own properties can be accessed, which resulted in a property chain.

1, a data class attribute:

It is the definition of class variables, namely static variables or static data. They are bound to class the object belongs, not dependent on any instance of the class. Here corresponds to the type of data in front of the variable plus static.

Copy the code
class newClass(object):
    foo = 100
    
print newClass.foo      #100
newClass.foo+=100
print newClass.foo      #200
Copy the code

Class instance attributes and attribute is not the same.

2, method

The method has become class properties.

3, see the class attribute

Dictionary attributes __dict__ using built-in function dir () or subclass can.

Copy the code
class newClass(object):
    def foo(self):
        pass
print dir(newClass)
#['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'foo'] 
print newClass.__dict__   
#{'__dict__': <attribute '__dict__' of 'newClass' objects>, '__module__': '__main__', 'foo': <function foo at 0x00B00A30>, '__weakref__': <attribute '__weakref__' of 'newClass' objects>, '__doc__': None}
 
Copy the code

 

 

Copy the code
class newClass(object):
    """Python Class"""
    def foo(self):
        pass

print newClass.__name__     #newClass
print newClass.__doc__      #Python Class
print newClass.__bases__    #(<type 'object'>,)
print newClass.__base__     #<type 'object'>
print newClass.__module__   #__main__
print newClass.__class__    #<type 'type'>
Copy the code

 

Third, examples

1. Examples of class

A class is a data structure type is defined, Examples of this type of variable is declared.

Copy the code
newClass class (Object): 
    "" "the Python Class" "" 
    DEF foo (Self): 
        Pass 

C = newClass () 
Print type (C) # <class '. newClass in __main __'>, and before release Python2.2 Examples is "examples of type" never consider the class from which the 
Print type (0) # <type 'int'> 
Print type (newClass) # <type 'type'> 
Print type (int) # <type 'type'> two those are the type of
Copy the code

Note that after the 2.2 version, when the definition of a new class, you have created a new type.

 

2, __ init __ () "constructor" method

Not by creating new instances, you do not define a constructor, you create objects in Python

__init __ () method is the first after the interpreter to create an instance for your call

If no special method is defined (or covering) the __init __ (). Examples of the pair does not impose any special operation.

 

3, __ new __ () "constructor" method

Compared with __init __ (), __ new __ () is more like a real constructor.

 

4, __ del __ () "destructor" method

 

Fourth, the class instance attributes and attribute

Reference: http://www.pythonfan.org/thread-9827-1-1.html

The python class attribute is an irrelevant instance storing data associated with the class, and class. Class attributes and java static member variables are similar. Python class attributes may be accessed using the class name + "." + Mode attribute name, if there is no instance of the class with the same name instance variables can also be used to access. If instance attribute contains the same name and the class attribute, the access attribute with the instance, is an example of access attributes.

 

Copy the code
the Test class ():    
      myversion = "1.0" # declare a class attribute, and assigned 1.0 
  
T = the Test () # generates an instance   
Test.myVersion # access class using the class attribute space, the output is 1.0 
t.myVersion Example # class attribute space, the output is 1.0 
Test.myVersion = "2.0" # class using the class attribute space to update 
Test.myVersion # access class using the class attribute space, the output is 2.0 
t.myVersion example # class attribute space The output is 2.0
Copy the code

 

 

Only use class space reference properties, in order to set and update class attributes. If you try to use the example of a spatial reference properties to be updated, the instance (if not the same name attribute words) creates an instance of the class attributes and attribute of the same name. The instance properties will prevent access to the instance of the class attribute, property of the same name until the instance is removed.

 

t.myVersion = '3.0' # t creates an instance is 'myVersion' instance attribute 
Test.myVersion # 2.0 output, the statement will not have any impact on class property 
t.myVersion # output 3.0, t visit is itself an instance attribute 
del t.myVersion # Clear t instance attribute 
t.myVersion # 2.0 output at this time is a class attribute access

 

However, in the case of variable-class attributes, not the same thing the

Copy the code
Test.x = { 'myVersion': ' 1.0'} # Test class to add a new class attribute 
Test.x # of space with access to the output attribute { 'myversion': '1.0'} 
TX # instance with access to the space output attribute { 'myversion': '1.0'} 
TX [ 'myversion'] = '2.0'   
: TX output # { '2.0' 'myversion'} 
{ 'myversion': '2.0'} Test.x example # t # output the class attribute update into effect 
del tx # error: t instance has no attribute 'x '
Copy the code

Guess you like

Origin www.cnblogs.com/cmybky/p/11772720.html