Python basics-class

Source: Internet
Author: User

Python basics-class

All object-oriented languages have classes.

Today, I will share with you a little bit about classes in Python, focusing on comparison with classes in C ++.

In C ++, the parent class is called superclass in Python)

Create class

class Person: def setName(self, name):   self.name = name def getName(self):   return self.name def greet(self):   print "Hello, world! I'm %s. " % self.name

This keyword in C ++, called self in Python
It seems that the self keyword is more vivid.

Binds a feature to a common function.

>>>class Class:     def method(self):       print 'I have a self!'>>>def function():     print "I don't...">>>instance = Class()>>>instance.method()I have a self!>>>instance.method = function>>>instance.method()I don't...

Private
Python does not have a private keyword. Whether it is a method change or a feature, add a Double underline before the name:

class Secretive:  def __inaccessible(self):    print 'Bet you can't see me...'

Specify the superclass
That is, the parent class and inheritance in C ++. The colon is not used here, but the superclass are written in the brackets behind the subclass:

class Filter:  def init(self):    self.blocked = []class SPAMFilter(Filter):  def init(self):    self.blocked = ['SPAM']

Check inheritance
As far as I know, there is no direct method in C ++ to determine whether two classes have parent-child relationships.
There are built-in methods in Python. The issubclass function:

>>>issubclass(SPAMFilter, Filter)true>>>issubclass(Filter, SPAMFilter)false

The only thing to note is that the first parameter is a subclass and the second parameter is a superclass.

Check whether an object is an instance of a class.
Isinstance method. The first parameter is the instance, and the second parameter is the class name.

Multiple superclasses
That is, the multiple inheritance mentioned in C ++, that is, several classes are written in parentheses, separated by commas.

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.