"Python" Python object-oriented programming notes

Source: Internet
Author: User

1. Creation of classes

A class is a data structure that we can use to define objects, which fuse data values with behavioral characteristics. Classes are abstract entities of the real world that appear in a programmatic manner. Instances are the materialization of these objects.

Class names are usually preceded by uppercase letters. It's standard practice.

class First ():     Pass if __name__ ' __main__ ' :     = First ()    = 3    = 5    print(f.x + f.y)

2. Methods

The self parameter , which is present in all method declarations. This parameter represents the instance object itself , which is silently passed to the method by the interpreter when you invoke the method with the instance, so you do not need to pass self in as it is automatically passed in.

The final way to invoke a method

(a) Defining classes (and methods)

(b) Create an instance

(c) The last step, use this instance to invoke the method.

class First ():     def Raiseup (self):         Print ("raise it up! " if__name__'__main__':    = First ()     = 3    = 5    print(f.x + f.y)    f.raiseup ()

Calling methods directly through the class name First.raiseup ()

D:\Python\Python35\python.exe d:/pycharmprojects/pythonoo/Ff2.pytraceback (most recent):   " d:/pycharmprojects/pythonoo/ff2.py "  in <module>    'self'1

Binding:

To be consistent with OOP conventions, Python is strict, and there are no instances where methods cannot be called . This restriction is the binding concept (binding)described by Python, where the method must be bound (to an instance) to be called directly. A non-binding method may be called , but the instance object must be explicitly given in order to ensure that the call succeeds. However, regardless of whether or not it is bound, the method is the intrinsic property of the class in which it resides, even though they are almost always invoked through an instance.

3. __init__ ()

After Python creates an instance, it calls the __init__ () method during instantiation, and when a class is instantiated, it is possible to define additional behavior, such as setting an initial value or running some preliminary diagnostic code ——— primarily after the instance is created, before the instantiation call returns to the instance. To perform certain tasks or settings. I don't understand the last sentence .

When object F is instantiated, its f.name is set.

Class First ():

def __init__ (self,name):
Self.name = Name
Print ("hi!" + Self.name + "!) Be prepared for raising it up! ")

def raiseup (self):
Print ("Raise It up!")

if __name__ = = ' __main__ ':

f = First (' Alex ')
F.raiseup ()

Run

D:\Python\Python35\python.exe d:/pycharmprojects/pythonoo/ for raising it up! Raise it up! Process finished with exit code 0

4. Inheritance

In Python, when a class is derived, the subclass inherits the properties of the base class, so in the above class, we define not only the __init__ (), Updatemail () method, but also second inherits the Raiseup () method from first.

If required, each subclass is best defined by its own constructor, otherwise the constructor of the base class is called. However, if the subclass overrides the constructor of the base class, the constructor of the base class will not be called automatically -so that the constructor of the base class must be explicitly written out to be executed, such as first.__init__ (Self,name)

Here we are going to explicitly pass the Self instance object to the base class constructor, because instead of invoking that method in its instance , we call that method in a subclass instance. Because we are not invoking it through an instance, this unbound method call needs to pass an appropriate instance (self) to the method.

classFirst ():def __init__(self,name): Self.name=namePrint("hi!"+ Self.name +"! Be prepared for raising it up!")    defRaiseup (self):Print("Raise It up!")classSecond (first):def __init__(self,name,weapon): first.__init__(self,name) self.weapon=WeaponPrint("hi!"+ Self.name +"! Be prepared for raising it up! with"+self.weapon)defRaiseupwith (self):Print("raise it up! with"+self.weapon)if __name__=='__main__': S= Second ('Alex','Python') S.raiseup () S.raiseupwith ()

Run

D:\Python\Python35\python.exe d:/pycharmprojects/pythonoo/ for for raising It up! With Pythonraise  it up! Raise it up! withpythonprocess finished with exit code 0

If you do not re-__init__ the subclass, you can use the __init__ of the parent class when instantiating

classFirst ():def __init__(self,name): Self.name=namePrint("hi!"+ Self.name +"! Be prepared for raising it up!")    defRaiseup (self):Print("Raise It up!")classSecond (first):defRaiseupwith (self):Print("raise it up! with"+self.weapon)if __name__=='__main__':    #s = Second (' Alex ', ' Python ')s = Second ('Alex') S.raiseup () S.raiseupwith ()

D:\Python\Python35\python.exe d:/pycharmprojects/pythonoo/first.py
Hi! alex! Be prepared for raising it up!
Traceback (most recent):
Raise It up!
File "d:/pycharmprojects/pythonoo/first.py", line, in <module>
S.raiseupwith ()
File "d:/pycharmprojects/pythonoo/first.py", line +, in Raiseupwith
Print ("Raise it up! with "+ self.weapon)
Attributeerror: ' Second ' object has no attribute ' weapon '

Process finished with exit code 1

5. Properties

The data properties of the class

The Data property is simply a variable of the class that is defined . They can be used like any other variable after the class is created, and are either updated by the methods in the class, or are updated somewhere else in the main program.

That is, static variables, or static data . They represent that the data is bound to the class object to which they belong and does not depend on any class instance. If you are a Java or C + + programmer, this type of data is equivalent to adding the static keyword before a variable declaration.
Static members are typically used only to track values associated with a class.

class Attri ():     " Class attribute Test " if __name__ ' __main__ ' :     Print (attri.arrtitest) D:\Python\Python35\python.exe D:/pycharmprojects/pythonoo/class_attribute.py  class  attribute testprocess finished with exit code 0

To view the properties of a class

Print(dir (Second))['__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__',
'__getattribute__','__gt__','__hash__','__init__','__le__','__lt__','__module__','__ne__',
'__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__',

'__subclasshook__','__weakref__','Raiseup','Raiseupwith']Print(Second.__dict__){'Raiseupwith': <function second.raiseupwith at 0x0000015aefe46598>
'__module__':'__main__','__doc__': None,'__init__': <function Second.__init__At 0x0000015aefe46510>}

Special class Properties

Print (Second. __name__ ) Secondprint(Second.  __base__)<class'__main__. first'>print(Second.  __module__)__main__print(Second.  __class__)<class'type'>

"Python" Python object-oriented programming notes

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.