Is it possible to create private methods for Python classes?

Asked

Viewed 31 times

2

In Rust, it is possible to create a module where some methods associated with a struct are private. I understand that the utility of this is to make available to the end user of the module only the important methods for use, while the private methods are used for internal tasks of those who created and/or maintain the module.

Example:

pub struct Player {
    pub username: String,
    pub email: String,
    pub age: u32,
    pub rating: f64,
    pub active: bool,
}

impl Player {
    pub fn double_age(&self) -> u32 {
        return 2*self.age
    }
}

impl Player {
    fn half_rating(&self) -> f64 {
        return 0.5*self.rating
    }
}

If this module is imported by another file, then the end user will only have access to the method double_age, marked as public (pub), but will not have access to half_rating (private by default).

Is there an equivalent of this feature in Python? I often create methods for classes in certain packages that I would like to use only internally, without making it available to the end user.

  • 2

    Python has no private methods. There may be names started with __ to avoid conflict of qualification. Many people think this is a kind of private method, but no. They have questions about the __ preceding the method name here at Sopt, but I’m not finding.

  • 2

    I was wondering if it would be duplicate, so see if this answer helps you: https://answall.com/a/189172/5878

  • 2

    He has the following other question: https://answall.com/q/53028/5878

  • 2

    In addition to the links above, it also contains: https://answall.com/q/186982/112052 | https://stackoverflow.com/a/64985332 | https://answall.com/q/447903/112052

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.