Introduction to Python Classes

Source: Internet
Author: User

Properties + Methods-Class (data and functions)

classTurtle ():#class name conventions in uppercase    #Propertiescolor =#Method    defClimb (self):Pass    defRun (self):PassTT= Turtle ()#Creating ObjectsTt.run ()#calledclassMyclass (list): Inherit listPassList2=Myclass () list2.append (4) List2.append (3) List2.sort ()

Encapsulation: Information Hiding technology

Inheritance: The mechanism by which subclasses automatically share data and methods between parent classes

Polymorphism: Different objects respond differently to the same method

What is self? Equivalent to C + + 's this pointer!

A class can generate countless objects, and when a method of an object is called, the object passes itself as the first argument to the self parameter, and Python knows which object is calling the method. For example:

Class Ball ():    def setName (self, name):        self.name = name    def kick (self):        print ("My name is%s, who kicks me ...) "% self.name) A = Ball () a.setname (' Qiu a ') b = Ball () b.setname (' Qiu B ') A.kick () B.kick ()

 

Python's Magic method (surrounded by a double glide line)

__init__ (self) Construction method for instantiating an object incoming parameter

Top two examples do not have the explicit declaration constructs the method, the trial default no miserable __init__ ()

# Coding:utf8 class Ball :         def __init__ (self, name):                 = name        def  Kick (self):                print("iam%s, damn, who kicked me  " %= Ball (' potatoes ') A.kick ()
c = Ball () #报错

Public and private?

Public can be accessed through the dot operator

Private variables (Name adaptation "_ Class name __ variable name") simply precede the variable name or function name with "__" two underscores! At this point name or point __name can not access to (error), Trial getname ()

# Coding:utf8 class Person :         __name " Liyi "        def GetName (self):                 return self. __name  = Person ()#p.name error #p.__name error p.getname ( ) P._person__name

Inherited

#Coding:utf8classParent:defHello (self):Print('Parent class Method Hello')        deffunc (self):Print('Parent class method Func')classChild (Parent):deffunc (self):Print('Subclass method Func, overriding the parent class method') P=Child () P.hello () P.func () [[email protected]~]#python test.pyParent class Method Hello Subclass method Func, overriding parent class method#Coding:utf8ImportRandom as R
classFish:def __init__(self): self.x= R.randint (0, 10) Self.y= R.randint (0, 10) defMove (self): self.x-= 1Print("my position is:", self.x, SELF.Y)classGoldfish (Fish):PassclassCarp (Fish):PassclassSalmon (Fish):PassclassShark (Fish):def __init__(self):
Fish.__init__ (self) #调用父类的构造方法, the self is the instance object of the subclass, which is equivalent to fish.__init__ (Shark) because it is overridden
A Better approach: supper (). __init__ (), which automatically puts all of the parent, parent class methods
Self.hungry=TruedefEat (self):ifself.hungry:Print("A foodie's dream is to eat every day.") Self.hungry=FalseElse: Print("It 's too much to eat.") G=goldfish () s=Shark () s.eat () G.move ( )

Multiple inheritance: It can make the grammar confusing, try not to

class Base1:     Pass class Base2:     Pass class C (Base1, Base2):     Pass

Combinatorial classes: Putting the instantiation of a class into a new class (horizontal relationship)

#Coding:utf8classTurtle:def __init__(self, x): Self.num=xclassFish:def __init__(self, x): Self.num=xclassPool:def __init__(delf, X, y): Self.turtle=x self.fish=ydefPrint_num (self):Print("the pool has a total of turtles%d, small fish%d"% (Self.turtle.num, self.fish.num)

Mix-in mechanism

Pass

Class, Class object, instance object: three different things!

# Coding:utf8 class C: #类         == = C () A.count #实例对象C. Count () #类对象

Properties and methods are the same, properties will overwrite the method! Attribute names with nouns, method names with verbs

Python Binding Concepts

Python's rigorous approach requires an instance to be called, which is actually what Python calls a binding concept. So you need to add self to the method definition

A.__dict__ viewing the properties owned by an instance

a.__dict__ see the properties that the class has, you can see the methods, and there are a lot of things to keep track of the values associated with the class. Instance objects are shared, but are overridden by instance properties

bif built-in functions for classes and objects

Issubclass (class, ClassInfo) if the first parameter is a subclass of the second argument, return True, Note:

    • Non-strict (oneself can be considered to be their own subclass);
    • The second parameter can be a tuple of more than one class, with any appropriate, true;
    • Other cases to throw TypeError

Isinstance (object, ClassInfo) checks whether an instance object of the first argument belongs to a class

    • The second parameter can be a tuple of more than one class, with any appropriate, true;
    • Always returns False if the first parameter passed in is not an object type
    • If the second argument is not a class or a tuple consisting of a class object, it throws a TypeError

Point manipulation Symbols Access object properties, attribute Related:

The Hasattr (object, Name) object has a set property name,name need to be enclosed in quotation marks, otherwise he will think of it as a variable,

GetAttr (object, name [, default]) Gets the name property of the object, if it does not exist, returns the default, if no default is set, it will be thrown if it does not exist attributeerror

    • GetAttr (A, ' B ', ' The property you are accessing does not exist ')

SetAttr (object, name, value) sets the value of the object Name property to a new property if the property does not exist

Delattr (object, name) removes the established property if it is not thrown attributeerror

Property () To set properties by property,

    • X = Property (GetSize, SetSize, delsize) set an X attribute that can manipulate GetSize, setSize, Delsize (write in advance) method
    • X can be used as a calling interface, the method can be changed, such as changing the name, etc., to increase the method.
    • How it works: combining several magical methods

Magic method

    • Surrounded by a double upper glide line
    • The Magic method is all about object-oriented python, and if you don't know the Magic method, you're not yet aware of the power of object-oriented python (not the Python script)

__init__ (self [,...]) Method

    • When not written, there will be a default without a parameter, write will overwrite
    • Must return none, no return, otherwise return TypeError

__new__ (cls[, ...])

    • The first method called when an object is instantiated, before Init, it has a big difference. The first parameter is not self, but this class, which returns an object
    • Rarely rewritten when you inherit an immutable type and need to be modified, you need to rewrite the new

class Capstr (str):    # Inheriting Str class is not becoming    def__new__(CLS, string):    # rewriting new, the first class to pass in, the other name does not matter, just to distinguish        string = String.upper ()    # all becomes uppercase        return str.__new__(CLS, String)    = capstr ('ILove Money')

__del__ (self) destructor

    • Delete abbreviation, which is called when all references to the object are automatically destroyed by Del.
    • Not executing del x is calling x.__del__ ()

Introduction to Python Classes

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.