Andrew Hudson - Fedora™ Unleashed, 2008 edition

Здесь есть возможность читать онлайн «Andrew Hudson - Fedora™ Unleashed, 2008 edition» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2008, ISBN: 2008, Издательство: Sams Publishing, Жанр: ОС и Сети, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Fedora™ Unleashed, 2008 edition: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Fedora™ Unleashed, 2008 edition»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Quick Glance Guide
Finding information you need is not always easy. This short index provides a list of common tasks discussed inside this book. Browse the table of contents or index for detailed listings and consult the specified chapter for in-depth discussions about each subject.
left How Do I…?
See…
How Do I…?
See…
left Back up my system?
Chapter 13
Partition a hard drive?
Appendix B, Chapters 1, 35
left Build a new Linux kernel?
Chapter 36
Play MP3s and other music?
Chapter 7
left Burn a CD?
Chapter 7
Print a file?
Chapter 8
left Change a password?
Chapter 4
Read a text file?
Chapter 4
left Change the date and time?
Chapter 32
Read or send email?
Chapter 21
left Compress a file?
Chapter 13
Read or post to newsgroups?
Chapter 5
left Configure a modem?
Chapter 2
Reboot Fedora?
Chapter 1
left Configure a printer?
Chapter 8
Rescue my system?
Chapter 13
left Configure a scanner?
Chapter 7
Set up a DNS server?
Chapter 23
left Configure a sound card?
Chapter 7
Set up a firewall?
Chapter 14
left Configure my desktop settings?
Chapter 3
Set up a web server?
Chapter 15
left Connect to the Internet?
Chapter 5
Set up an FTP server?
Chapter 20
left Control a network interface?
Chapter 14
Set up Samba with SWAT?
Chapter 19
left Copy files or directories?
Chapters 13, 32
Set up wireless networking?
Chapter 14
left Create a boot disk to boot Fedora?
Chapter 1
Shut down Fedora?
Chapter 1
left Create a database?
Chapter 16
Use a spreadsheet?
Chapter 6
left Create a user?
Chapter 4
Use Instant Messaging?
Chapter 5
left Delete a file or directory?
Chapter 32
Watch television on my computer?
Chapter 7
left Get images from a digital camera?
Chapter 7
Edit a text file?
Chapter 4
left Install Fedora?
Chapter 1
Make Fedora more secure?
Chapter 14
left Log in to Fedora?
Chapter 1
Mount a CD-ROM or hard drive?
Chapter 35

Fedora™ Unleashed, 2008 edition — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Fedora™ Unleashed, 2008 edition», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Having a custom constructor is great when you need to accept a set of parameters for each object being created. For example, you might want each dog to have its own name on creation, and you could implement that with this code:

class dog(object):

def __init__(self, name):

self.name = name

fluffy = dog("Fluffy")

print fluffy.name

If you do not provide a nameparameter when creating the dogobject, Python reports an error and stops. You can, of course, ask for as many constructor parameters as you want, although it is usually better to ask for only the ones you need and have other functions fill in the rest.

On the other side of things is the destructor method, which allows you to have more control over what happens when an object is destroyed. Using the two, you can show the life cycle of an object by printing messages when it is created and deleted:

class dog(object):

def __init__(self, name):

self.name = name print

self.name + " is alive!"

def __del__(self):

print self.name + " is no more!"

fluffy = dog("Fluffy")

The destructor is there to give you the chance to free up resources allocated to the object or perhaps log something to a file.

Class Inheritance

Python allows you to reuse your code by inheriting one class from one or more others. For example, cars, trucks, and motorbikes are all vehicles, and so share a number of similar properties. In that scenario, you would not want to have to copy and paste functions between them; it would be smarter (and easier!) to have a vehicle class that defines all the shared functionality and then inherit each vehicle from that.

Consider the following code:

class car(object):

color = "black"

speed = 0

def accelerateTo(self, speed):

self.speed = speed

def setColor(self, color):

self.color = color

mycar = car()

print mycar.color

This creates a carclass with a default color and also provides a setColor()function so that people can change their own colors. Now, what do you drive to work? Is it a car? Sure it is, but chances are it is a Ford, or a Dodge, or a Jeep, or some other make — you don't get cars without a make. On the other hand, you do not want to have to define a class Ford, give it the methods accelerateTo(), setColor(), and however many other methods a basic car has and then do exactly the same thing for Ferrari, Nissan, and so on.

The solution is to use inheritance: Define a carclass that contains all the shared functions and variables of all the makes and then inherit from that. In Python, you do this by putting the name of the class from which to inherit inside parentheses in the class declaration, like this:

class car(object):

color = "black"

speed = 0

def accelerateTo(self, speed):

self.speed = speed

def setColor(self, color):

self.color = color

class ford(car): pass

class nissan(car): pass

mycar = ford()

print mycar.color

The passdirective is an empty statement — it means the class contains nothing new. However, because the fordand nissanclasses inherit from the carclass, they get color, speed, accelerateTo(), and setColor()provided by their parent class. Note that you do not need objectafter the classnames for fordand nissanbecause they are inherited from an existing class: car.

By default, Python gives you all the methods the parent class has, but you can override that by providing new implementations for the classes that need them. For example:

class modelt(car):

def setColor(self, color):

print "Sorry, Model Ts come only in black!"

myford = ford()

ford.setColor("green")

mycar = modelt()

mycar.setColor("green")

The first car is created as a Ford, so setColor()works fine because it uses the method from the car class. However, the second car is created as a Model T, which has its own setColor()method, so the call will fail.

This provides an interesting scenario: What do you do if you have overridden a method and yet want to call the parent's method also? If, for example, changing the color of a Model T was allowed but just cost extra, you would want to print a message saying, "You owe $50 more," but then change the color. To do this, you need to use the class object from which the current class is inherited — car, in this example. Here's an example:

class modelt(car):

def setColor(self, color):

print "You owe $50 more"

car.setColor(self, color)

mycar = modelt()

mycar.setColor("green")

print mycar.color

That prints the message and then changes the color of the car.

Multiple Inheritance

You can inherit as many classes as you need, building up functionality as you go. For example, you could have a class animalia, a subclass chordata, a sub-subclass mammalia, and a sub-sub-subclass homosapiens. Each one is more specific than its parent. However, an interesting addition in Python is the capability to have multiple inheritance — to take functionality from two classes simultaneously.

Again, this is best shown in code:

class car(object):

def drive(self):

print "We're driving..."

class timemachine(object):

def timeTravel(self):

print "Traveling through time..."

class delorian(car,timemachine): pass

mydelorian = delorian()

mydelorian.drive()

mydelorian.timeTravel()

In that example, you can see a class carand a class timemachine. Both work by themselves, so you can have a car and drive around in it or a time machine and travel through time with it. However, there is also a delorianclass that inherits from carand timemachine. As you can see, it is able to call both drive()(inherited from car) and timeTravel()(inherited from timemachine).

This introduces another interesting problem: What happens if both carand timemachinehave a refuel()function? The answer is that Python picks the correct function to use based on the order in which you listed the parent classes. The previous code used class delorian(car,timemachine), which means "inherit from carand then from timemachine." As a result, if both classes had a refuel()function, Python would pick car.refuel().

This situation becomes more complex when further inheritance is involved. That is, if carinherits its refuel()method from vehicle, Python still chooses it. What happens behind the scenes is that Python picks the first class from which you inherited and searches it and all its parent classes for a matching method call. If it finds none, it goes to the next class and checks it and its parents. This process repeats until it finds a class that has the required method.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Fedora™ Unleashed, 2008 edition»

Представляем Вашему вниманию похожие книги на «Fedora™ Unleashed, 2008 edition» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Fedora™ Unleashed, 2008 edition»

Обсуждение, отзывы о книге «Fedora™ Unleashed, 2008 edition» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x