Python learning diary-Object-Oriented Programming (1), python Object-Oriented Programming

Source: Internet
Author: User

Python learning diary-Object-Oriented Programming (1), python Object-Oriented Programming

Python class and instance)

Assume that a shoe has two attributes: size and color.

Class can play a role in the template. Therefore, when creating an instance, you can forcibly enter some attributes that we think must be bound. By defining a special__init__When creating an instance, bind the size and color attributes to shoe. For example:

1 class Shoe(object):2 3     def __int__(self, size, color):4         self.size = size5         self.color = color

(Object) indicates the class to inherit from. If there is no suitable inheritance class, the object is used;

Self indicates the instance itself. Therefore, you can use the _ int _ method to add attributes to self;

 

Data encapsulation

Define the function for accessing data from the class so that data can be encapsulated. For example:

1 class Shoe(object):2 3     def __init__(self, size, color):4         self.size = size5         self.color = color6 7     def get_color(self):8         print('%s: %s' % (self.size, self.color))

To define a method, except that the first parameter isselfAnd other functions.

To call a method, you only need to call it directly on the instance variable,selfNo need to pass. Other parameters are passed in normally:

>>> bart.get_color()32: black

Another advantage of encapsulation is thatStudentClass to add new methods, suchget_grade:

 1 class Shoe(object): 2     ... 3  4     def get_level(self): 5         if self.size >= 40: 6             return 'A' 7         elif self.size >= 32: 8             return 'B' 9         else:10             return 'C'

You can simply call get_level, for example:

>>>46.get_level()'A'

NOTE: Refer to teacher Liao Xuefeng's website http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431864715651c99511036d884cf1b399e65ae0d27f7e000

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.