"Python" Import class

Source: Internet
Author: User

Importing a single class

As you continue to add classes that may make your files very long, you need to store the classes in the module and then import the classes in the main program to

book.py

classBook ():" "simulate a book" "    def __init__(self,name,page,year): Self.name=name Self.page=page Self.year= YeardefGet_describe_book (self):" "returns the descriptive information of the book read" "Long_name= str (self.year) +' page '+str (self.page) +' '+self.name return long_name

my_book.py

 from Import  = Book ('Pride and Prejudice', 352,1796)print(my_book.get_ Describe_book ())

In the above code, the from book Import book is the class book imported from the book module.

Storing multiple classes in a module

Although there should be some correlation between classes in the same module, you can store as many classes as you want in a module

classWoman ():" "describe a woman" "    def __init__(self,name,age): Self.name=name Self.age= Agedefdescribe (self):return("My name is"+ Self.name +"and I ' m"+str (self.age) +"years old" )classMan ():" "describe a man" "    def __init__(self,name,age): Self.name=name Self.age= Agedefdescribe (self):return("My name is"+ Self.name +"and I ' m"+str (self.age) +"years old")
Importing multiple classes from a module

Import the above file in woman and man class

 from Import  = Woman ('Alice', +)print= Man ('  Zhangsan', at $)print(Alice.describe ())
Import the entire module

The above import class is very troublesome, you need to know the class name in this module can be imported, for convenience, we can directly import the entire class

Import= people. Woman ('Alice', +)print= people. Man ('zhangsan', ')print(Alice.describe ())

Also available as: from people import * (not recommended)

If the A module relies on the B module and the B module relies on the C module, then you can import C into the B module before importing to the A module

"Python" Import class

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.