Python classes and examples


A class is a template for an instance, and an instance is an object built on the basis of a class. Classes and instances are two of the most important concepts in object-oriented programming.

Instances (or objects) created from the same class have the same methods, but they can each have different data.

kind

A class is an abstraction of the same thing (i.e., the same part of a thing), and the keyword class is used in python to define a class.

classPerson:

pass

The above generation defines an empty kind, should kind There is no properties harmony approach。 be affiliated with kind The variables we call kind of properties, be affiliated with kind The function we call kind of approach。

properties

There are two types of properties, subordinate to a class itself or subordinate to an instance of the touch a class. Those that are subordinate to the examples of the class we call example properties, and those that are subordinate to the class itself we call class properties.

Properties can be bound to instances via instance variables or the self keyword

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

classPerson:

def__init__(self,name):

self.name=name

person=Person('Bob')

person.age=31

print(person.name)

print(person.age)

print(Person.name)

print(Person.age)

The above code executes with the following result

Bob

31

Traceback (most recent call last):

File"class.py", line13,in

print(Person.name)

AttributeError: type object'Person'has no attribute'name'

The above code uses the instance person and self to define the attributes age and name respectively. When accessing the attributes, you can get the values of age and name through the instance person normally, but when using the class Person to access the attributes age and name, the python prompttype object 'Person' has no attribute 'name' The attribute name does not exist for the class Person.

If the class Person itself needs a property, it can be defined directly in the class, which belongs to the Person class itself and is accessible to all examples instantiated by Person.

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

classPerson:

name='Person'

def__init__(self,age):

self.age=age

person1=Person(23)

person2=Person(33)

print(Person.name)

print(person1.name)

print(person1.age)

print(person2.name)

print(person2.age)

The above code executes with the following result

Person

Person

23

Person

33

The above code shows that the attribute name is defined directly in the class and can be accessed not only by the class Person, but also by Person's instances person1 and person2.

The example property is only available within the example. Class properties are available not only to classes, but also to instances instantiated by that class.

Since class properties are available in instances of the class, what happens at this point when the instance properties and class properties are the same, let's look at the following code.

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

classPerson:

name='Person'

def__init__(self,name,age):

self.name=name

self.age=age

person=Person('Bob',33)

print(person.name)

print(person.age)

print(Person.name)

The above code runs as follows

Bob

33

Person

As you can see from the above code, when the class property and the instance property are the same, the instance property does not override the value of the class property; it is the instance property that is obtained when accessed through the instance, and the class property that is obtained when accessed through the class.

When writing code try to avoid situations where the class and instance properties are the same, because then the instance property will override the class property and may give a different result than expected.

In the code we see above the properties of the class or example are visible to all, in fact the original intention of using classes was to hide the internal data and manipulate it through methods, which is contrary to our original intention as of now. So what do you do if you want to hide internal properties? We can prefix the names of properties with two underscores, and in Python, a variable name of an instance that starts with __ becomes a private variable (private), accessible only internally and not externally. We modify the above code as follows.

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

classPerson:

def__init__(self,name,age):

self.__name=name

self.__age=age

defprint_age():

print("%s age is %s"%(self.name,self.age))

person=Person('Bob',33)

person.print_age()

print(person.__age)

The above code runs as follows

Bob age is33

Traceback (most recent call last):

File"", line14,in

AttributeError:'Person'object has no attribute'__age'

As shown above kind of properties No direct access, This ensures that external code cannot modify the internal state of the object at will, This is protected by access restrictions, More robust code。 But if you want to access or modify the internal properties What to do about it, We can increase the number of options by adding get harmony set approach come true。

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

classPerson:

def__init__(self,name,age):

self.__name=name

self.__age=age

defprint_age():

print("%s age is %s"%(self.name,self.age))

defget_name():

returnself.__name

defget_age():

returnself.__age

defset_name(name):

self.__name=name

defset_age(age):

self.__age=age

person=Person('Bob',33)

person.print_age()

print(person,get_age())

person.set_age(34)

print(person,get_age())

The above code runs as follows

Bob age is33

33

34

approach

kind of approach both... (and...) kind Functions in, Unlike ordinary functions kind of approach The first parameter is self, But after calling the approach You do not need to pass in self。 beyond, kind of approach There is no difference from the normal function, So you can still use the default parameters、 variable parameter、 Keyword parameters and named keyword parameters。

The self parameter in the method is required, even if there are no other parameters.

You always see the __init__ method in the previous code. The __init__ method is a special method of the class that has a name of Initialization function , which runs as soon as the class is instantiated, and it can perform initialization operations on any target object you need to manipulate. As used in the previous example, you don't have to call the function explicitly; python calls it automatically during the instantiation of the class.

It is important to note that in__init__ approach There are two underscores in front and two in back。


Recommended>>
1、Burnsides Lemma and Polyas Theorem
2、A yearend summary from a 6year Java programmer written for those of you still in a funk
3、BZOJ2152Congenial Coco point splitting rule
4、The importance of hybrid cloud and how to get started with it
5、Third Quarter Mobile Industry Data Report

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号