有没有C和Python的等价物来代替Java中的public和private?

huangapple go评论89阅读模式
英文:

Is there a C and Python equivalent of Java's public and private?

问题

我意识到我学过的许多语言中都包括关键字 publicprivate,我还发现 Lua 中相当于 private 的关键字是 local,这让我想知道在 C 和 Python 中是否也有类似的对应关键字。

那么在 C 和 Python 中是否有 Java 中 publicprivate 的真正等价之处呢?

英文:

I realized that in many languages I have learned includes the keywords public and private, and I also found out that Lua's equivalent to private is local which got me thinking if there is also an equivalent in C and Python.

So is there an actual equivalent of Java's public and private in C and Python?

答案1

得分: 3

以下是要翻译的内容:

在Python中,存在一种用于受保护和私有字段的命名约定:
一个下划线前缀表示受保护,两个下划线表示私有。但这并没有严格强制执行。更多详情请参阅:
https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python

所有未以一个或两个下划线作为前缀的内容都是公共的。

在C语言中,全局变量和函数可以从其他源文件的函数中访问,除非它们被声明为“static”。虽然不完全与“private”相同,但C语言不是面向对象的,因此这里不存在类的概念。

英文:

There is a naming convention for protected and private fields in Python:
A prefix of one underscore means protected, two underscores mean private. But this is not really enforced. More details here:
https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python

Everything not prefixed with one or two underscores is public.

In C, global variables and functions can be accessed from functions in other source files unless they are declared static. Not exactly the same as private, but C is not object-oriented so the concept of a class does not exist here.

答案2

得分: 0

在Python中,您可以通过在成员名称之前添加双下划线来声明私有成员,就像这样:

class Sample:
    def __init__(self):
        self.__private_mem = "只能被成员函数访问的内容"
        self.public_mem = "可以在类外部作为对象属性访问的内容"

sample = Sample()
print(sample.public_mem)
print(sample.__private_mem) # 会引发错误

但是,我想在C语言中没有这样的东西,因为它不是面向对象的。

英文:

In python you can declare private members by putting dunders(double underscore) before member name, like this :

class Sample:
    def __init__(self):
        self.__private_mem = "Can be accessed only by member functions"
        self.public_mem = "Can be accessed as object properties outside the class"

sample = Sample()
print(sample.public_mem)
print(sample.__private_mem) # will raise an Error

But, I guess there is no such thing in C language as it is not object oriented.

huangapple
  • 本文由 发表于 2020年10月13日 15:32:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64330599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定