Python Object-oriented basics

Source: Internet
Author: User
Tags instance method

Python Object-oriented basics What is object-oriented programming?

Object-oriented programming is a paradigm of programming, which calls the program as a different object, and is an object model for the real world.

The basic idea of object-oriented programming

i.e. classes and instances

    • Class: A class is a type used to define abstractions. Like people, it's a kind of thing.
    • Instances: Instances are created based on the definition of the class. For example, Little Red classmate, is based on the attributes of people created.
# 我们通过class关键字定义一个类class Person:    pass# 通过类来创建一个实例,即类名加上一个类似于函数的调用来创建实例= Person()
    • Data encapsulation: Data encapsulation is an important feature of object-oriented
class Person:    def__init__(self):        self= name  # 初始化实例的属性,self代表的是当前实例= Person('XiaoHong')
Property Access Restrictions

We can bind a lot of attributes to an instance, and we can make those properties inaccessible externally by adding double underscores (__) at the beginning of the property name.

Look at the following example:

classPerson:def __init__( Self, name): Self. Name=Name Self. _title= ' Mr '  # Single Underline         Self. __job= ' Student ' # Double underline indicates private property# Create a person instanceP=Person (' Tom ')Print(P.name)Print(P._title)Print(P.__job)=Tommr---------------------------------------------------------------------------AttributeerrorTraceback (most recent)<Ipython-input-1-0815b282cdc2> inch <Module>()7P=Person (' Tom ')8 Print(P.name)----> 9 Print(P.__job)Attributeerror: person instance have no attribute' __job ' 

Thus, the double underscore ' __job ' cannot be accessed directly by the outside.
But the problem is that if the attribute is defined in the form of 'xxx', it can be accessed externally.
Because attributes defined with 'xxx' are called special attributes in Python classes, such as __init__/CMP/str/__int__ and so on, these are pre-defined special properties of the class. Typically we do not define attributes in this form.
It is worth to note that, with a single underline, should not be external access, in the end why, I do not know.

To create a property for a class

A class is a template, and an instance is an object created from a class.
Instance properties Each instance owns, is independent of each other, and the class attribute has only one copy.
When a class property and an instance property name conflict, the instance property is selected first.

class  person:job =   ' Student '  def  __init__   (self , name): self . Name =  Name# create a person instance  P1 =  person ( ' Tom ' ) p2 =  Person ( ' Jak ' ) print  (person.job) # direct access to the properties of the class  # because Python is a dynamic language, the nature of the class is also an object, and the properties of all classes can be dynamically added and modified  person.job =  Span class= "st" > ' Teacher '  print  (person.job) # instance properties each instance owns and is independent of each other.  print  (p1.name) print  (p2.name) =>  Studentteachertomjak  

As a result, each instance of an instance property has its own, independent, and only one copy of the class attribute.

Defining instance methods

The private property of an instance is a property that begins with a double underscore and cannot be accessed externally, but is internally accessible.
An instance method is a function that is defined in a class, and its first argument is always self, pointing to the instance that invokes the method.
Within an instance method, all instance properties can be accessed, and can be obtained through a method call if external access to the instance properties is required.

class Person:    def__init__(self, name):        self= name    def get_name(self):        returnself= Person('Tom')print(p1.get_name())=>Tom

Everything is connected to objects, classes and functions are objects.

= Person('Tom')print(p1)print(p1.get_name)print(p1.get_name())=><0x000000000BBAD448><<0x000000000BBAD448>>Tom

Methods for creating classes

Similar to attributes, methods are also divided into instance methods and class methods.
All defined in a class are instance methods, and the first argument of an instance method is the instance itself.
The method of defining a class in a class requires the use of @classmethod on the method

class Person(object):    =0    @classmethod    def how_many(cls):        # 统计该类的实例个数        return cls.count    def__init__(self, name):        self= name        =+1print= Person('Bob')print Person.how_many()=>01
Conclusion

This is just a brief introduction to object-oriented, if you want to go deeper, read more.
If there is any wrong, please correct me.

Python Object-oriented basics

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.