Python class and instance, Python class instance

Source: Internet
Author: User

Python class and instance, Python class instance

The most important concepts of object-oriented are Class and Instance. You must remember that classes are abstract templates, such as Student classes, instances are specific "objects" created based on classes. Each object has the same method, but its data may be different. Although it is essentially the same as C # or JAVA, there is still a certain gap in writing.

Taking the Student class as an example, in Python, the definition class isclassKeyword, followed by the parameter.

class Student(object):    pass

Generally, objects are replaced without inheritance. If Python wants to use relevant attributes, the self keyword is used. This is a bit like the constructor in C #, but no relevant attributes need to be declared in Python.

>>> Class Student (object ):... def _ init _ (self, name, age ):... self. name = name... self. age = age >>>>>> a = Student ('zhang san', 24) >>>. name zhang San>. age24

At the same time, you can not only add your own attributes, but also write methods.

>>> class Dog(object):...            def Eat(self):...                 print('i am dog')>>>a=Dog()>>>a.Eat()i am dog

At the same time, the returned value is no different from the function.

>>>class Dog(object):...         def Myname(self):...               return 'my name is dog'...>>>b=Dog()>>>b.Myname()my name is dog

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.