Python Study Notes (6) and python Study Notes

Source: Internet
Author: User

Python Study Notes (6) and python Study Notes

I. Classes and Instances

The first object-oriented program:

class Student(object):    def __init__(self, name, score):        self.name = name        self.score = score    def print_score(self):        print '%s: %s' % (self.name, self.score)bart = Student('Bart Simpson', 59)lisa = Student('Lisa Simpson', 87)bart.print_score()lisa.print_score()
The class name is generally a word starting with an upper case. (object) indicates the class from which the class inherits.

_ Init _ is similar to the constructor in Java. The property is initialized. The parameter self indicates the created instance itself. self does not need to be passed during the call, the python interpreter will pass in the instance variables.


Ii. Access Restrictions

The variable name of the class instance starts with _ and becomes a private variable, which can only be accessed internally and cannot be accessed externally.

If the variable name starts with a double underline and ends with a double underline (_ xxx _), it is a special variable. Special variables can be accessed directly, indicating private variables.

If the variable name starts with an underscore (_ xxx), such instance variables can be accessed outside, but according to conventions, when you see such variables, it means, "Although I can be accessed, please think of me as a private variable and do not access it at will"


How to access private variables? Like Java, get and set methods are defined:

class Student(object):    def __init__(self, score):        self.score = score    def get_name(self):        return self.__name    def set_score(self, score):        self.__score = score

Iii. Inheritance and Polymorphism

Benefits of inheritance: subclasses can obtain all the functions of the parent class, and of course subclasses can also override the methods of the parent class.

class Animal(object):    def run(self):        print 'Animal is running...'class Dog(Animal):    def run(self):        print 'Dog is running...'class Cat(Animal):    def run(self):        print 'Cat is running...'animal = Animal();animal.run() # Animal is running...dog = Dog() dog.run() # Dog is running...cat = Cat()cat.run() # Cat is running...        

Polymorphism: multiple forms of A Class. For example, dog can be regarded as animal, cat can also be regarded as animal.

class Animal(object):    def run(self):        print 'Animal is running...'            def run_twice(self, animal):        animal.run()class Dog(Animal):    def run(self):        print 'Dog is running...'class Cat(Animal):    def run(self):        print 'Cat is running...'animal = Animal()dog = Dog() cat = Cat()animal.run_twice(animal) # Animal is running...animal.run_twice(dog) # Dog is running...animal.run_twice(cat) # Cat is running...
Benefits of polymorphism: When we need to pass in Dog and cat, we only need to accept the Animal type, because Dog and cat are all Animal types. For a variable, we only need to know that it is an Animal type, and you can call the run () method with confidence without knowing its child type exactly. Therefore, any type of input, as long as it is an Animal class or subclass, the actual type of run () method is automatically called, which is polymorphism.

4. Get Object Information

You can use isinstance () to determine whether a variable is of a certain type ()

A = list () # a is list type B = Animal () # B is Animal type c = Dog () # c is Dog type print isinstance (a, list) # Trueprint isinstance (B, Animal) # Trueprint isinstance (c, Dog) # True

Determine the object type:

import typestype('abc')==types.StringType  # True
You can use getattr (), setattr (), and hasattr () to directly manipulate the status of an object:

Operation object attributes:

>>> Hasattr (obj, 'x') # Is there an attribute 'X? True >>> obj. x9 >>> hasattr (obj, 'y') # Is there an attribute 'y? False >>> setattr (obj, 'y', 19) # Set an attribute 'y' >>> hasattr (obj, 'y') # Do you have an attribute 'y? True >>> getattr (obj, 'y') # Get the property 'y' 19 >>> obj. y # Get the property 'y' 19
Operation object method:

Hasattr (obj, 'power') # Do you have the 'power' attribute? Getattr (obj, 'power') # obtain the attribute 'power' fn = getattr (obj, 'power') # obtain the attribute 'power' and assign the value to the variable fn. fn points to obj. powerfn () # Call fn () and call obj. power () is the same

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.