Python learning class definitions in -11.python

Source: Internet
Author: User
Tags instance method

Python is an object-oriented language, and as an object-oriented feature-class is also available. It is worth noting that everything in Python is object, not like in C # for performance reasons, int is also an object in Python. (int is struct in C #)

How to define a class:

1 class Person : 2     Pass

Use class keyword, which defines a person class. But now this class is blank.

Next, define a constructor function

1 class Person : 2     def __init__ (self,name,age): 3         Self.name=name4         self.age=age

The function __init__ is the name of the constructor for a class in Python, and the name of any Python class constructor must be.

In the __init__ constructor, the first argument self refers to the instance. This is well understood, because the constructor is also an instance function. In Python, defining an instance function requires that the self parameter be filled in the first argument of the function.

Next, you define an instance function and a static function.

1 classPerson :2     def __init__(self,name,age):3Self.name=name4Self.age= Age5 6     defPrintname (self):7         Print(Self.name)8 9     defstaticprint ():Ten         Print('This class\ ' s name was person')

The next step is to create a new instance of the class and call it.

1 Instance=person ('Tom')2instance.printname ()  3 person.staticprint ()

The first line invokes the constructor of the person and assigns the instance to the instance variable. It is worth noting that there is no new keyword in python.

The second line invokes the instance method of the Printname. Output Tom.

The third line invokes the Staticprint static method of the person class, outputting this class's name is the person.

Python learning class definitions in -11.python

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.