Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the classes and objects of python

Shulou Source: shulou.com Published: 2022-06-01 03:54:37 09月28日 Update

Most people do not understand the knowledge points of this article "python classes and objects are used", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "python classes and objects how to use" article.

Classes-like

Enter:

#! / usr/bin/python

# Filename: simplestclass.py

Class Person:

Pass

# An empty block

P = Person ()

Print (p)

Output:

$python simplestclass.py

Explanation:

Definition declaration of the class

Class class name

The use of the class requires initializing the declaration

P = Person ()

Output as attributes of class p

Method of object

Enter:

#! / usr/bin/python

# Filename: method.py

Class Person:

Def sayHi (self):

Print ('Hello, how are you?')

P = Person ()

P.sayHi ()

# This short example can also be written as Person () .sayHi ()

Output:

$python method.py

Hello, how are you?

Explanation:

The function defined in the parent class can be used after the subclass is initialized.

P = Person ()

P.sayHi ()

_ _ init__ method

Enter:

#! / usr/bin/python

# Filename: class_init.py

Class Person:

Def _ _ init__ (self, name):

Self.name = name

Def sayHi (self):

Print ('Hello, my name is',self.name)

P = Person ('Swaroop')

P.sayHi ()

# This short example can also be written as Person ('Swaroop'). SayHi ()

Output:

$python class_init.py

Hello, my name is Swaroop

Explanation:

The _ _ init__ method is called automatically when all classes are initialized. In this example, the init method is used to get the parameters passed in at initialization.

The self function represents the calling variable itself.

In this example, Swaroop is passed in during initialization, and the assignment of name can be called directly when other functions are called.

The above is about the content of this article on "how python classes and objects are used". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Tags: Content objects methods outputs functions explanations inputs articles knowledge articles values parameters variables most subclasses that is attributes more steps knowledge points Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information macOS vpn Redmi NVidia