Python Notes-Class definitions

Source: Internet
Author: User

Python Notes-Class definitions

First, class definition:

Class < category name:

< statements >

After a class is instantiated, its properties can be used, and in fact, after a class is created, its properties can be accessed through the class name

If you modify its properties directly using the class name, it will directly affect the object that has already been instantiated

Private properties of the class:

__private_attrs two underscores, declares that the property is private and cannot be used outside of the class or accessed directly

When used in methods inside a class Self.__private_attrs

Methods of the class

Inside the class, using the DEF keyword, you can define a method for a class that differs from a generic function definition, which must contain the parameter self, and is the first argument

Private class methods

__private_method two underscores, declares that the method is a private method and cannot be called outside of a class

Calling Slef.__private_methods inside a class

The proprietary methods of the class:

The __init__ constructor, which is called when the object is generated

__del__ destructors, using when releasing objects

__repr__ Printing, converting

__setitem__ Assignment by index

__getitem__ getting values by index

__len__ Get length

__CMP__ comparison operations

__call__ function call

__add__ Plus arithmetic

__SUB__ Reduction Operations

__mul__ Multiply operation

__DIV__ in addition to operations

__mod__ Calculating the remainder

__pow__ said Fang

Example:

#类定义
class people:
#定义基本属性
Name = ' '
Age = 0
#定义私有属性, private properties cannot be accessed directly outside the class
__weight = 0
#定义构造方法
def __init__ (self,n,a,w):
Self.name = n
Self.age = A
Self.__weight = W
def speak (self):
Print ("%s is speaking:i am%d years old"% (self.name,self.age))
p = people (' Tom ', 10,30)
P.speak ()

Python Notes-Class definitions

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.