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 修饰符

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
修饰符(decorators)是Python的一种特殊语法,用于修改函数或的行为。它们是通过在函数或定义之前使用@符号,后跟修饰符函数或的方式来实现的。 修饰符函数接受被修饰的函数作为参数,并返回一个新的函数或修改原始函数。这样,当调用被修饰的函数时,实际上会执行修饰后的函数。 修饰符主要用于以下几个方面: 1. 扩展函数的功能:可以在不修改原始函数代码的情况下,通过添加修饰符来增加额外的功能。 2. 函数注册:可以使用修饰符将函数注册到某个心,以便在其他地方使用。 3. 访问控制:可以使用修饰符来限制对某些函数或的访问权限。 下面是一个简单的示例,演示如何使用修饰符来记录函数的执行时间: ```python import time def timeit(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time = end_time - start_time print(f"函数 {func.__name__} 的执行时间为 {execution_time} 秒") return result return wrapper @timeit def my_function(): # 函数的具体实现 time.sleep(1) my_function() ``` 在上面的例子,`timeit` 是一个修饰符函数,它接受被修饰的函数作为参数,并返回一个新的函数 `wrapper`。`wrapper` 函数记录了被修饰函数的执行时间,并在执行结束后打印出来。通过在 `my_function` 函数定义之前使用 `@timeit` 修饰符,`my_function` 函数就会被修饰并添加了计时功能。 希望这个例子能帮助你理解修饰符的概念和用法。如果还有其他问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值