Python Constructor Learning Notes

Source: Internet
Author: User

in the Python Development (http://www.maiziedu.com/course/python-px/) there is a function called a constructor in the programming language, and in this function there is a key word called self, and thefirst thing that is clear is that it will only be in the method of the class, independent function or method is not necessary with Self the. Let's talk about How to use the Self keyword in the constructor.

Structure

Class FooBar:

def _int_ (self):

Self.somevar = the

>>>f = FooBar ()

>>>f.somevar the

Rewrite

Class A:

def hello (self):

print "Hello, I ' m A"

Class B (A):

def hello (self):

print "Hello, I ' m B"

b = B ()

B.hello ()

Hello, I ' m B

Property

Class Rectangle:

def _init_ (self):

self.width = 0

self.height = 0

def setSize (sef, size):

Self.width, self.height = size

def getsize (self):

return self.width, Self.height

Use:

R = Rectangle ()

R . Width  =  Ten

R . Height  =  5

R . GetSize () # (5)

R . SetSize (+- ) # (+)

Property function  
is to wrap the attributes above:

Class Rectangle:

def _init_ (self):

self.width = 0

self.height = 0

def setSize (sef, size):

Self.width, self.height = size

def getsize (self):

return self.width, Self.height

Size = Property (GetSize, SetSize)

Use:

R = Rectangle ()

R . Width  =  Ten

R . Height  =  5

R . Size # (5)

R . Size (+- ) # (+)

Static Methods  
Adorner @

Class MyClass:

@staticmethod

def smeth ():

print ' This is a static method '


Python Constructor Learning Notes

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.