Python object-oriented-class properties and instance properties

Source: Internet
Author: User

#coding: utf-8# describes the class orange:    def __init__ (self, weight) of the Orange object:         self.weight = weight  #实例属性     def  get_weight (self):         print (self.weight) Class HostInfo:     info = []  #类属性     def add_host (self,  HOSTNAME, IP):         self.info.append ({"hostname": hostname,   "IP": IP})     def get_info (self):         print (self.info) if __name__ ==  "__main__":     o1 = orange ( 1.5)   #橘子1   weight 1.5    o2 = orange (2.3)   #橘子2   weight 2.3     o1.get_weight ()   #获取重量     o2.get_weight () #橘子1的重量是1.5, Orange 2 weighs 2.3, This so-called weight (data) is called a property, and the property is usually variable, #橘子类的每一个实例都会有重量This property, but the given data for each instance's properties will be different or the same     h1 = hostinfo ()   #对象h1增加数据      h1.add_host ("PC", "192.168.1.2")     h2 = hostinfo ()   #对象h2增加两条数据     h2.add_host ("PC", "192.168.1.2")     h2.add_host ("PC", "192.168.1.2")     h1.get_info ()   #不管是谁添加, everyone can get the host information,     h2.get_info () # Conclusion: Class properties are shared across all instances, and instance properties belong only to the instance itself


Python object-oriented-class properties and instance properties

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.