python 修饰符_Python访问修饰符

python 修饰符

In most of the object-oriented languages access modifiers are used to limit the access to the variables and functions of a class. Most of the languages use three types of access modifiers, they are - private, public and protected.

在大多数面向对象的语言中,访问修饰符用于限制对类的变量和函数的访问。 大多数语言使用三种类型的访问修饰符,它们是privatepublicprotected

Just like any other object oriented programming language, access to variables or functions can also be limited in python using the access modifiers. Python makes the use of underscores to specify the access modifier for a specific data member and member function in a class.

与其他面向对象的编程语言一样,也可以使用访问修饰符在python中限制对变量或函数的访问。 Python使用下划线指定类中特定数据成员和成员函数的访问修饰符。

Access modifiers play an important role to protect the data from unauthorized access as well as protecting it from getting manipulated. When inheritance is implemented there is a huge risk for the data to get destroyed(manipulated) due to transfer of unwanted data from the parent class to the child class. Therefore, it is very important to provide the right access modifiers for different data members and member functions depending upon the requirements.

访问修饰符在保护数据免受未经授权的访问以及防止数据被操纵方面起着重要的作用。 当实现继承时,由于不需要的数据从父类转移到子类,因此存在很大的数据被破坏(操纵)的风险。 因此,根据需求为不同的数据成员和成员函数提供正确的访问修饰符非常重要。

Python:访问修饰符的类型 (Python: Types of Access Modifiers)

There are 3 types of access modifiers for a class in Python. These access modifiers define how the members of the class can be accessed. Of course, any member of a class is accessible inside any member function of that same class. Moving ahead to the type of access modifiers, they are:

Python中的类有3种类型的访问修饰符。 这些访问修饰符定义了如何访问类的成员。 当然,可以在同一类的任何成员函数内部访问类的任何成员。 进入访问修饰符的类型,它们是:

访问修饰符:公共 (Access Modifier: Public)

The members declared as Public are accessible from outside the Class through an object of the class.

可以通过类的对象从类外部访问声明为Public的成员。

访问修饰符:受保护 (Access Modifier: Protected)

The members declared as Protected are accessible from outside the class but only in a class derived from it that is in the child or subclass.

可以从类外部访问声明为“受保护”的成员,但只能在子类或子类中从其派生的类中访问。

访问修饰符:专用 (Access Modifier: Private)

These members are only accessible from within the class. No outside Access is allowed.

这些成员只能从班级内部访问。 不允许外部访问。

时间来一些例子 (Time for some Examples)

In this section we will provide some basic code examples for each type of access modifier.

在本节中,我们将为每种类型的访问修饰符提供一些基本的代码示例。

public访问修饰符 (public Access Modifier)

By default, all the variables and member functions of a class are public in a python program.

默认情况下,类的所有变量和成员函数在python程序中都是public

# defining a class Employee
class Employee:
    # constructor
    def __init__(self, name, sal):
        self.name = name;
        self.sal = sal;

All the member variables of the class in the above code will be by default public, hence we can access them as follows:

上面代码中该类的所有成员变量默认都是public ,因此我们可以按以下方式访问它们:

>>> emp = Employee("Ironman", 999000);
>>> emp.sal;
999000

protected访问修饰符 (protected Access Modifier)

According to Python convention adding a prefix _(single underscore) to a variable name makes it protected. Yes, no additional keyword required.

根据Python约定,在变量名后添加前缀_ (单个下划线)可使其得到protected 。 是的,不需要其他关键字。

# defining a class Employee
class Employee:
    # constructor
    def __init__(self, name, sal):
        self._name = name;   # protected attribute 
        self._sal = sal;     # protected attribute

In the code above we have made the class variables name and sal protected by adding an _(underscore) as a prefix, so now we can access them as follows:

在上面的代码中,我们通过添加_ (下划线)作为前缀来使类变量名称sal protected ,因此现在我们可以按以下方式访问它们:

>>> emp = Employee("Captain", 10000);
>>> emp._sal;
10000

Similarly if there is a child class extending the class Employee then it can also access the protected member variables of the class Employee. Let's have an example:

同样地,如果有扩展类的子类Employee的话还可以访问类的保护成员变量Employee 。 让我们举个例子:

# defining a child class
class HR(Employee):
    
    # member function task
    def task(self):
        print ("We manage Employees")

Now let's try to access protected member variable of class Employee from the class HR:

现在,让我们尝试从HR类访问Employee类的受保护成员变量:

>>> hrEmp = HR("Captain", 10000);
>>> hrEmp._sal;
10000
>>> hrEmp.task();
We manage Employees

private访问修饰符 (private Access Modifier)

While the addition of prefix __(double underscore) results in a member variable or function becoming private.

加上前缀__ (双下划线)会导致成员变量或函数变为private

# defining class Employee
class Employee:
    def __init__(self, name, sal):
        self.__name = name;    # private attribute 
        self.__sal = sal;      # private attribute

If we want to access the private member variable, we will get an error.

如果要访问私有成员变量,则会收到错误消息。

>>> emp = Employee("Bill", 10000);
>>> emp.__sal;

AttributeError: 'employee' object has no attribute '__sal'

AttributeError:“员工”对象没有属性“ __sal”

多合一示例 (All in one Example)

Now that we have seen each access modifier in separate examples, now let's combine all that we have learned till now in one example:

既然我们已经在单独的示例中看到了每个访问修饰符,现在让我们在一个示例中结合到目前为止所学的内容:

# define parent class Company
class Company:
    # constructor
    def __init__(self, name, proj):
        self.name = name      # name(name of company) is public
        self._proj = proj     # proj(current project) is protected
    
    # public function to show the details
    def show(self):
        print("The code of the company is = ",self.ccode)

# define child class Emp
class Emp(Company):
    # constructor
    def __init__(self, eName, sal, cName, proj):
        # calling parent class constructor
        Company.__init__(self, cName, proj)
        self.name = eName   # public member variable
        self.__sal = sal    # private member variable
    
    # public function to show salary details
    def show_sal(self):
        print("The salary of ",self.name," is ",self.__sal,)

# creating instance of Company class
c = Company("Stark Industries", "Mark 4")
# creating instance of Employee class
e = Emp("Steve", 9999999, c.name, c._proj)

print("Welcome to ", c.name)
print("Here ", e.name," is working on ",e._proj)

# only the instance itself can change the __sal variable
# and to show the value we have created a public function show_sal()
e.show_sal()

Now the code above show the correct usage of public, private and protected member variables and methods. You can try and change a few things a run the program to see what error those changes result into.

现在,上面的代码显示了publicprivateprotected成员变量和方法的正确用法。 您可以尝试更改一些内容,然后运行程序以查看这些更改导致的错误。

演示地址

翻译自: https://www.studytonight.com/python/access-modifier-python

python 修饰符

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值