Declaring a variable in a class (outside of a function): all class functions can access it (basically a public variable)
Declaring a variable inside a function inside a class: only that function can access it (it's in that function's scope)
Declaring a variable with self.(variable name)
inside a function inside a class: all class functions can access it (how is this different from global (variable name)
?)
And since there is no private/protected, everything is public, so everything accessible from inside a class is accessible from outside the class.
Are there any other nuances I should know, or have I pretty much got it?
Class variables can be modified by referring to them by class name (e.g. Class. x = 5 ) and all instances will inherit these changes. Instance variables are private to an instance and can only be modified by that instance. You can achieve some level of access control using underscores.
What is Variable Scope in Python? In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.
Summary. PHP has four types of variable scopes including local, global, static, and function parameters.
A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters.
Since the listing in your question is not 100% clear, I've decided to explain it with a simple example. It also includes some things like __something
variables you did not mention in your list.
class Test: a = None b = None def __init__(self, a): print self.a self.a = a self._x = 123 self.__y = 123 b = 'meow'
At the beginning, a
and b
are only variables defined for the class itself - accessible via Test.a
and Test.b
and not specific to any instance.
When creating an instance of that class (which results in __init__
being executed):
print self.a
doesn't find an instance variable and thus returns the class variableself.a = a
: a new instance variable a
is created. This shadows the class variable so self.a
will now reference the instance variable; to access the class variable you now have to use Test.a
self._x
creates a new instance variable. It's considered "not part of the public API" (aka protected) but technically it has no different behaviour.self.__y
creates a new instance variable named _Test__y
, i.e. its name is mangled so unless you use the mangled name it cannot be accessed from outside the class. This could be used for "private" variables.b
creates a local variable. It is not available from anywhere but the __init__
function as it's not saved in the instance, class or global scope.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With